How to use Counter Controlled While Loop
Submitted by GeePee on Monday, May 18, 2015 - 21:54.
The following Java program uses Counter Controlled While Loops. Suppose you know exactly how many times certain statements need to be executed. In such cases, while loops assumes the form of a counter-controlled while loops. Suppose that a set of statements need to be executed N times. You can set up a counter to track how many items have been read. . I will be using the JCreator IDE in developing the program.
To start in this tutorial, first open the JCreator IDE, click new and paste the following code:
Sample run:
- import java.util.*;
- public class CounterControlled
- {
- {
- int limit;
- int number;
- int sum;
- int counter;
- limit = console.nextInt();
- sum = 0;
- counter = 0;
- while (counter < limit)
- {
- number = console.nextInt();
- sum = sum + number;
- counter++;
- }
- if (counter != 0)
- else
- }
- }
Enter data for processing:
12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8
The sum of the 12 numbers = 335
The average = 27
The preceding program works as follows: the statement System.out.println("Enter the data for processing:");
prompts the user to input the data for processing.
The statement limit = console.nextInt();
reads the next input line and stores it in the variable limit. The value of limit indicates the number of items to be read.
The statements sum = 0;
and counter = 0;
initialize the variables sum and counter to 0.
The while statement while (counter < limit)
checks the value of counter to determine how many have been read. If the counter is less than limit, the while loop proceeds for the next iteration.
The statement number = console.nextInt();
stores the next number in the variable number.
The statement sum = sum + number;
updates the value of sum by adding the value of number to the previous value.
The statement counter++;
increments the value of counter by 1.
The statement System.out.println(" The sum of the number is = " + sum);
outputs the sum of the numbers.
The statement [geshifilter-java if (counter != 0)
System.out.println(" the average is = " + (sum / counter));
else
System.out.println("no input data");
Comments
Add new comment
- Add new comment
- 352 views