Counter-controlled while loop statements - JAVA tutorial with PRACTICAL example
Coding River
Counter-controlled while loops
Hi and welcome back to this channel Today, I would like to talk to you about Counter-controlled while loops Actually, in Java programming, the while loop can take various forms In this video, I will show how to use the counter-controlled while loop This counter-controlled while loop is used when you know exactly how many times your while loop action statements need to be executed.
For example, if you want to create a program in which a set of statements need to execute a specific number of times. You can then set a counter that will be used to control or track how many times the action statement is executed.
Let’s use the example on the screen illustrate
int counter = 0
while (counter less than 10) { System.out.println(“The output statement is executed ” + counter + “ times”); counter ++; }
This portion of code is a typical example of a counter-controlled while loop We have started by setting up and initializing a counter variable that will be used to track the number of times the action statement will be executed
Next, we have the loop condition that is used to test the counter variable or the loop control variable The number 10 here, represents the number of times the action statement needs to execute If the value of the variable counter is less than 10, the statements in the body of the while loop execute. The loop will continue to execute until the value of the counter is greater than or equal to 10
In the body of the while statement, the action statements are executed as long as the loop condition is true Also, the value of the variable counter is incremented and updated as long as the loop condition is true
Let’s take another example that will be a bit more complex and allow us to understand how to use the counter-controlled while loop
In this example, we are going to create a program that will calculate the summation and the average of numbers entered by the user in our program
We will use some of the concepts we saw in the previous videos as well
Since we want the program to prompt the user to enter data using the keyboard So we need to add an input object
public class CounterControlledWhileLoop { static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
Next, we have to declare the various variables that will be used in the program The first one will be a variable that will store the numbers entered by the user int number;
Second, the variable that will hold the summation and the average int sum, average;
Next, we will declare a variable that will limit the number of integer values the user will be authorized to enter int limit;
Finally, since we will use a counter-controlled while loop in this program Let’s declare a counter int counter;
18457216 Bytes