The while Loop
Tags: java, programming, learning, beginners
Published: 2024-05-08 13:26:57

A **while** loop executes statements repeatedly while the condition is true.

The syntax for the **while** loop is:

```
while (loop-continuation-condition) {
 // Loop body
 Statement(s);
}
```

The left diagram in the image below is the **while**-loop flowchart. The part of the loop that contains the statements to be repeated is called the _loop body_. A one-time execution of a loop body is referred to as an _iteration (or repetition) of the loop_. Each loop contains a _loop-continuation-condition_, a Boolean expression that controls the execution of the body. It is evaluated each time to determine if the loop body is executed. If its evaluation is **true**, the loop body is executed; if its evaluation is **false**, the entire loop terminates and the program control turns to the statement that follows the **while** loop.

The loop for displaying **Welcome to Java!** a hundred times introduced in the preceding section is an example of a **while** loop. Its flowchart is shown in the right diagram below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bapyddf42minpq09viu.png)

The **loop-continuation-condition** is **count < 100** and the loop body contains the following two statements:

```
int count = 0;
while (count < 100) {
 // loop body
 System.out.printIn("Welcome to Java!");
 count++;
}
```
In this example, you know exactly how many times the loop body needs to be executed because the control variable **count** is used to count the number of executions. This type of loop is known as a _counter-controlled loop_. The **loop-continuation-condition** must always appear inside the parentheses. The braces enclosing the loop body can be omitted only if the loop body contains one or no statement.

Here is another example to help understand how a loop works.

```
int sum = 0, i = 1;
while (i < 10) {
 sum = sum + i;
 i++;
}
System.out.println("sum is " + sum); // sum is 45
```

If **i < 10** is **true**, the program adds **i** to **sum**. Variable **i** is initially set to **1**, then is incremented to **2**, **3**, and up to **10**. When **i** is **10**, **i < 10** is **false**, so the loop exits. Therefore,
the sum is **1 + 2 + 3 + ... + 9 = 45**.
What happens if the loop is mistakenly written as follows?

```
int sum = 0, i = 1;
while (i < 10) {
 sum = sum + i;
}
```

This loop is infinite, because **i** is always **1** and **i < 10** will always be **true**.

Make sure that the **loop-continuation-condition** eventually becomes **false** so that the loop will terminate. A common programming error involves infinite loops (i. e., the loop runs forever). If your program takes an unusually long time to run and does not stop, it may have an infinite loop. If you are running the program from the command window, press CTRL+C to stop it.

Programmers often make the mistake of executing a loop one more or less time. This is commonly known as the _off-by-one error_. For example, the following loop displays **Welcome to Java** 101 times rather than 100 times. The error lies in the condition, which should be **count < 100** rather than **count <= 100**.

```
int count = 0;
while (count <= 100) {
 System.out.println("Welcome to Java!");
 count++;
}
```

We can modify a program that prompts the user to enter an answer for a question on addition of two single digits. Using a loop, you can now rewrite the program to let the user repeatedly enter a new answer until it is correct.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c039jigxxtqy9npv3zhl.png)

The loop in lines 16-19 repeatedly prompts the user to enter an **answer** when **number1 + number2 != answer** is **true**. Once **number1 + number2 != answer** is **false**, the loop exits.

## Case Study: Guessing Numbers

The problem is to guess what number a computer has in mind. You will write a program that randomly generates an integer between **0** and **100**, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can make the next guess intelligently. Here is a sample run:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r12m3dnntn69a9lwc62t.png)

The magic number is between **0** and **100**. To minimize the number of guesses, enter **50** first. If your guess is too high, the magic number is between **0** and **49**. If your guess is too low, the magic number is between **51** and **100**. So, you can eliminate half of the numbers from further consideration after one guess.

How do you write this program? Do you immediately begin coding? No. It is important to _think before coding_. Think how you would solve the problem without writing a program. You need first to generate a random number between **0** and **100**, inclusive, then to prompt the user to enter a guess, and then to compare the guess with the random number.

It is a good practice to _code incrementally_ one step at a time. For programs involving loops, if you don’t know how to write a loop right away, you may first write the code for executing the loop one time, and then figure out how to repeatedly execute the code in a loop. For this program, you may create an initial draft, as shown below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6etpee6vv9bdldhdodrm.png)

When you run this program, it prompts the user to enter a guess only once. To let the user enter a guess repeatedly, you may wrap the code in lines 13-22 in a loop as follows:

```
while (true) {
// Prompt the user to guess the number
 System.out.print("\nEnter your guess: ");
 guess = input.nextInt();
if (guess == number)
 System.out.println("Yes, the number is " + number);
else if (guess > number)
 System.out.println("Your guess is too high");
else
 System.out.println("Your guess is too low");
} // End of loop
```

This loop repeatedly prompts the user to enter a guess. However, this loop is not correct, because it never terminates. When **guess** matches **number**, the loop should end. So, the loop can be revised as follows:

```
while (guess != number) {
// Prompt the user to guess the number
 System.out.print("\nEnter your guess: ");
 guess = input.nextInt();
if (guess == number)
 System.out.println("Yes, the number is " + number);
else if (guess > number)
 System.out.println("Your guess is too high");
else
 System.out.println("Your guess is too low");
} // End of loop
```

The complete code:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/186of4ra8k9p014odo9y.png)

The program generates the magic number in line 8 and prompts the user to enter a guess continuously in a loop (lines 14-25). For each guess, the program checks whether the guess is correct, too high, or too low (lines 19-24). When the guess is correct, the program exits the loop (line 14). Note that **guess** is initialized to **-1**. Initializing it to a value between **0** and **100** would be wrong, because that could be the number to be guessed.

## Loop Design Strategies

Writing a correct loop is not an easy task for novice programmers. Consider three steps when writing a loop.

- Step 1: Identify the statements that need to be repeated.
- Step 2: Wrap these statements in a loop like this:

```
while (true) {
 Statements;
}
```

- Step 3: Code the **loop-continuation-condition** and add appropriate statements for controlling the loop.

```
while (loop-continuation-condition) {
 Statements;
 Additional statements for controlling the loop;
}
```

## Case Study: Multiple Subtraction Quiz

A Math subtraction learning tool program that generates just one question for each run can be modified. You can use a loop to generate questions repeatedly. How do you write the code to generate five questions? Follow the loop design strategy. First identify the statements that need to be repeated. These are the statements for obtaining two random numbers, prompting the user with a subtraction question, and grading the question. Second, wrap the statements in a loop. Third, add a loop control variable and the **loop-continuation-condition** to execute the loop five times.
The program below generates five questions and, after a student answers all five, reports the number of correct answers. The program also displays the time spent on the test and lists all the questions.

```
package demo;
import java.util.Scanner;

public class SubtractionQuizLoop {

	public static void main(String[] args) {
		final int NUMBER_OF_QUESTIONS = 5; // Number of questions
		int correctCount = 0; // Count the number of correct answers
		int count = 0; // Count the number of questions
		long startTime = System.currentTimeMillis();
		String output = " "; // output string is initially empty
		Scanner input = new Scanner(System.in);
		
		while(count < NUMBER_OF_QUESTIONS) {
			// 1. Generate two single-digit integers
			int number1 = (int)(Math.random() * 10);
			int number2 = (int)(Math.random() * 10);
			
			// 2. If number1 < number2, swap number1 with number2
			if(number1 < number2) {
				int temp = number1;
				number1 = number2;
				number2 = temp;
			}
			
			// 2. Prompt the student to answer "what is number1 - number2?"
			System.out.print("What is " + number1 + " - " + number2 + "? ");
			int answer = input.nextInt();
			
			// 4. Grade the answer and display the result
			if(number1 - number2 == answer) {
				System.out.println("You are correct!");
				correctCount++; // Increase the correct answer count
			}
			else
				System.out.println("Your answer is wrong.\n" + number1 + " - " + number2 + " should be " + (number1 - number2));
			
			// Increase the question count
			count++;
			
			output += "\n" + number1 + "-" + number2 + "=" + answer + ((number1 - number2 == answer) ? " correct" : " wrong");
		} // End of loop
		
		long endTime = System.currentTimeMillis();
		long testTime = endTime - startTime;
		
		System.out.println("Correct count is " + correctCount + "\nTest time is " + testTime / 1000 + " seconds\n" + output);
	}

}

```

The program uses the control variable **count** to control the execution of the loop. **count** is initially **0** (line 9) and is increased by **1** in each iteration (line 39). A subtraction question is displayed and processed in each iteration. The program obtains the time before the test starts in line 10 and the time after the test ends in line 44, and computes the test time in line 45. The test time is in milliseconds and is converted to seconds in line 47.

## Controlling a Loop with a Sentinel Value

Another common technique for controlling a loop is to designate a special value when reading and processing a set of values. This special input value, known as a _sentinel value_, signifies the end of the input. A loop that uses a sentinel value to control its execution is called a _sentinel-controlled loop_.

The program below writes a program that reads and calculates the sum of an unspecified number of integers. The input **0** signifies the end of the input. Do you need to declare a new variable for each input value? No. Just use one variable named **data** (line 12) to store the input value and use a variable named **sum** (line 15) to store the total. Whenever a value is read, assign it to **data** and, if it is not zero, add it to **sum** (line 17).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5f9nz6t2bwepy36g4ezs.png)

If **data** is not **0**, it is added to **sum** (line 17) and the next item of input data is read (lines 20–21). If **data** is **0**, the loop body is no longer executed and the **while** loop terminates. The input value **0** is the sentinel value for this loop. Note that if the first input read is **0**, the loop body never executes, and the resulting sum is **0**.

Don’t use floating-point values for equality checking in a loop control. Because floatingpoint values are approximations for some values, using them could result in imprecise counter values and inaccurate results.
Consider the following code for computing **1 + 0.9 + 0.8 + ... + 0.1**:

```
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
 sum += item;
 item -= 0.1;
}
System.out.println(sum);
```

Variable **item** starts with **1** and is reduced by **0.1** every time the loop body is executed. The loop should terminate when **item** becomes **0**. However, there is no guarantee that item will be exactly **0**, because the floating-point arithmetic is approximated. This loop seems okay on the surface, but it is actually an infinite loop.

## Input and Output Redirections

In the preceding example, if you have a large number of data to enter, it would be cumbersome to type from the keyboard. You can store the data separated by whitespaces in a text file, say **input.txt**, and run the program using the following command:

```
java SentinelValue < input.txt
```

This command is called _input redirection_. The program takes the input from the file **input.txt** rather than having the user type the data from the keyboard at runtime. Suppose the contents of the file are 
`2 3 4 5 6 7 8 9 12 23 32
23 45 67 89 92 12 34 35 3 1 2 4 0`

The program should get **sum** to be **518**.

Similarly, there is _output redirection_, which sends the output to a file rather than displaying it on the console. The command for output redirection is:

```
java ClassName > output.txt
```

Input and output redirection can be used in the same command. For example, the following command gets input from **input.txt** and sends output to **output.txt**:

```
java SentinelValue output.txt
```

Try running the program to see what contents are in **output.txt**.