Java
TOPIC 20 – WHILE LOOPS – PART 2

AP EXTRA – COUNTING ITERATIONS

 

 

AP LESSON NOTE

 

 

COUNTING ITERATIONS

 

Many uses of WHILE loops involve the need to count the number of iterations that have occurred in a WHILE loop.

 

This is done very easily by using the following template:

 

       int count = 0;

      

       while(condition)

       {

           //do something here

          

           count++;

       }

 

SIMPLE EXAMPLE

In this example, the program continuously asks the user for a positive integer.  Once the user enters a negative integer, the looping ends and the total and count is outputted.

 

     int count = 0;

     int total = 0;

    

     Scanner scr = new Scanner(System.in);

     System.out.println("Enter an integer (Negative to exit.");

     int val = scr.nextInt();

          

     while(val >= 0)

     {

           total = total + val;

           System.out.println("Enter an integer (Negative to exit.");

           val = scr.nextInt();

           count++;

     }

     System.out.println("The total is " + total);

     System.out.println("You entered " + count + " positive numbers.");