While statement, counter and accumulator variables

The instruction or while statement allows us to execute statements repeatedly, while a condition is met.

Syntax:

while (<condition>) 
	<instruction>

Using a block of instructions, it would look like this:

while  (<condition>) {
	<sequence of statements separated by semicolons>
}

 

 

The first time the statement is reached, the condition is evaluated. If it is false, the program continues to the next statement without executing the statements inside the while. If the condition is true, the instructions inside the while are executed and the process is repeated.

Counter variable

When working with repetitive loops, we are often interested in knowing in which repetition we are in. To count repetitions, we use a variable called counter.

The technique is:

  1. Initialize a variable to zero or one, before the repeating cycle.

  2. Within the repetitive cycle, we increase the variable in one:

package com.edu4java.javatutorials;

public class WhileCounter {
	public static void main(String[] args) {
		int counter = 0;
		while (counter < 5) {
			counter = counter + 1;
			System.out.println(counter);
		}
	}
}
  

The example above, uses a counter variable to count the repetitions and prints on the console the number of each repetition: 1,2,3,4,5.

Accumulator variable

It is similar to the counter. It is initialized to zero and is incremented in each repetition with different values.

The result is that the variable accumulates the sum of the values added ​​in each repetition:

package com.edu4java.javatutorials;
import javax.swing.JOptionPane;

public class WhileCounterAcumulator {
	public static void main(String[] args) {
		int counter = 0;
		int accumulator = 0;
		while (counter < 5) {
			counter = counter + 1;
			accumulator = accumulator + Integer.parseInt(JOptionPane
				.showInputDialog("Enter the " + counter + "º number"));
		}
		JOptionPane.showMessageDialog(null, "The sum of the 5 numbers is " + accumulator);
	}
}

This program asks the user for 5 numbers and returns the sum. For this, a counter is used to control the number of times we ask the user for numbers and an accumulator to calculate the sum of the 5 numbers.