Loops in Java – while loop and for loop

In this post, you will learn to:

  • Identify the need for a loop and list the types of loops.
  • Explain the while statement and the rules associated with it.
  • Identify the purpose of the do-while statement.
  • State the need of for statement.
  • Describe nested loops.
  • Compare the different types of loops

Need for Loops

A computer program is a set of statements, which are usually executed sequentially. However, in certain situations, it is necessary to repeat certain steps to meet a specified condition.

For example, if the user wants to write a program that calculates and displays the sum of the first 10 numbers 1, 2, 3, …, 10.

One way to calculate the same is as follows:
1+2=3
3+3=6
6+4=10
10+5=15
15+6=21
… and so on.

This technique is suitable for relatively small calculations. However, if the program requires adding the first 200 numbers, it would be tedious to add up all the numbers from 1 to 200 using the mentioned technique. In such situations, iterations or loops come to our rescue.

Definition and Types

A loop comprises a statement or a block of statements that are executed repeatedly until a particular condition evaluates to true or false. Loops enable programmers to develop concise programs, which otherwise would require thousands of program statements.

The loop statements supported by Java programming language are:

  • while
  • do-while
  • for

‘while’ Statement

The while statement in Java is used to execute a statement or a block of statements while a particular condition is true. The condition is checked before the statements are executed. The condition for the while statement can be any expression that returns a boolean value.

The following is the syntax of while statement.

Syntax:

while (expression)
{
   // one or more statements
}

The following code demonstrates the use of while statement.

Code Snippet:

int num = 1;
while(num <= 5)
{
   System.out.printf("\n%d * 10 = %d",num,(num * 10));
   num++;
}

As shown in the code, a variable of type integer, num, is declared to store the number. The variable num is initialized to 1 and is used in the while loop to start multiplication from 1.

The condition num <= 5 ensures that the while loop executes as long as the value in num is less than or equal to 5. The execution of the loop stops when condition becomes false, that is, when the value of num reaches 6. The first statement within the body of the loop calculates the value of product by multiplying num with 10. The next statement prints this value and the last statement within the body of the loop changes the value of num by incrementing it by 1.

Output:

1 * 10 = 10
2 * 10 = 20
3 * 10 = 30
4 * 10 = 40
5 * 10 = 50

The body of the while loop will be empty if it contains a null statement and it is syntactically correct in Java. The following code demonstrates the use of a null statement using while loop.

Code Snippet:

.....
int num1 = 1;
int num2 = 30;
while(++num1 < --num2);
System.out.println("Midpoint is: " + num1);
.....

As shown in the code, the value of num1 is incremented and the value of num2 is decremented. These values are then compared with one another. The loop repeats till the value of num1 is equal to or greater than num2. Thus, upon exit num1 will hold a value that is midway between the original values of num1 and num2. The output of this code will be:

The midpoint is: 16

Rules

The following points should be noted when using the while statement:

  • The values of the variables used in the expression must be set at some point before the while loop is reached. This process is called the initialization of variables and has to be performed once before the execution of the loop.
  • The body of the loop must have an expression that changes the value of the variable that is a part of the loop’s expression. A variable is said to be incremented if its value increases in the body of the loop and is said to be decremented if its value decreases.

For example, if a while statement is written as follows:

while (true)
{
 . . .
}

The condition is simply a boolean value true. This leads to an infinite loop. The following code demonstrates the use of an infinite loop.

Code Snippet:

.....
int count = 0;
while(count < 100) {
   System.out.println("This goes on forever, HELP!!!");
   count = count + 10; \\Incrementing the value of count by 10.
   System.out.println("Count = " + count);
   count= count - 10; \\Decrementing the value of count by 10.
   System.out.println("Count = " + count);
}
.....

As shown in the code, the value of count is always 0, which is less than 100. So, the expression always returns a true value. Hence, the loop never ends. A break statement can be used to terminate such programs. Thus, it will just go into the loop once and terminate, displaying the output as:

This goes on forever, HELP!!!
Count = 10
Count = 0

However, this is not to be practiced in real world scenarios.

‘do-while’ Statement

The do-while statement checks the condition at the end of the loop rather than at the beginning to ensure that the loop is executed at least once. The condition of the do-while statement usually comprises of an expression that evaluates to a boolean value.

The following is the syntax of do-while statement.

Syntax:

do
{
 statement(s);
}
while (expression);

The following code demonstrates the use of do-while statement.

Code Snippet:

int num = 1, sum = 0;
do
{
    sum = sum + num;
    num++;
}
while(num <= 10);
System.out.printf("Sum = %d",sum);

As shown in the code, two integer variables, num and sum are declared and initialized to 1 and 0 respectively. The loop block begins with a do statement. The first statement in the body of the loop calculates the value of sum by adding the current value of sum with num and the next statement in the loop changes the value of num by incrementing it by 1. Next, the condition, num <= 10, included in the while statement is evaluated. If the condition is met, the instructions in the loop are repeated. If the condition is not met (that is, when the value of num becomes 11), the loop terminates and the value in the variable sum is printed.

Output:

Sum = 55

‘for’ Statement

The for loops are especially used when the user knows how many times the statements need to be executed in the code block of the loop. It is similar to the while statement in its function. The statements within the body of the loop are executed as long as the condition is true. Here too, the condition is checked before the statements are executed.

The following is the syntax of for statement.

Syntax:

for(initialization; condition; increment/decrement)
{
     // one or more statements
}

where,
initialization: initializes the variables that will be used in the condition.
condition: comprises the condition that is tested before the statements in the loop are executed.
increment/decrement: comprises the statement that changes the value of the variable (s) to ensure that the condition specified in the condition section is reached. Typically, increment and decrement operators, such as ++, –, and shortcut operators, such as += or -= are used in this section. Note, that there is no semicolon at the end of the increment/decrement expressions.

The three declaration parts are separated by semicolons. When the loop starts the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable and acts as a counter that controls the loop. The initialization expression is executed only once. Next, the boolean expression is evaluated. It usually tests the loop control variable against a targeted value. If the expression is true, then the body of the loop is executed and if the expression is false then the loop terminates. Lastly, the iteration portion of the loop is executed. This expression usually increments or decrements the loop control variable.

The following code demonstrates the use of for statement.

Code Snippet:

int num, product;
for(num = 1; num <= 5; num++)
{
   product = num * 10;
   System.out.printf("\n%d * 10 = %d ",num,product);
}

In the initialization section of the for loop, the num variable is initialized to 1. The condition statement, num <= 5, ensures that the for loop executes as long as num is less than or equal to 5. The loop exits when the condition becomes false, that is, when the value of num becomes equal to 6. Finally, the increment statement num++ in the increment/decrement section of the for statement increments the value of num by 1. The increment/decrement expression is evaluated after the first round of iteration.

Output:

1 * 10 = 10
2 * 10 = 20
3 * 10 = 30
4 * 10 = 40
5 * 10 = 50

The scope of the for loop can be extended by including more than one initialization or increment expressions in the for loop specification. The expressions are separated by the ‘comma’ operator and evaluated from left to right. The order of the evaluation is important if the value of the second expression depends on the newly calculated value.

The Following code demonstrates the use of for loop with the ‘comma’ operator to print the addition table for two variables.

Code Snippet:

.....
int i, j;
int max = 10;
System.out.println("The sum of two variables for a table of 10 is:");

for(i = 0, j = max; i <= max; i++, j--) {
    System.out.printf("\n%d + %d = %d", i, j, i+j);
}
.....

As shown in the code, three integer variables i, j, and max are declared. The variable max is assigned a value 10. Further, within the initialization section of the for loop, the i variable is assigned a value 0 and j is assigned the value of max, that is, 10. Thus, two parameters are initialized using a ‘comma’ operator. The condition statement, i <= max, ensures that the for loop executes as long as i is less than or equal to max that is 10. The loop exits when the condition becomes false, that is, when the value of i becomes equal to 11. Finally, the iteration expression again consists of two expressions, i++, j–. After each iteration, i is incremented by 1 and j is decremented by 1. The sum of these two variables which is always equal to max is printed.

The output of this code will be as follows:

The sum of two variables for a table of 10 is:
0 + 10 = 10
1 + 9 = 10
2 + 8 = 10
3 + 7 = 10
4 + 6 = 10
5 + 5 = 10
6 + 4 = 10
7 + 3 = 10
8 + 2 = 10
9 + 1 = 10
10 + 0 = 10

Alternatively, any or all expressions in the for loop may be left blank. The following code demonstrates the use of for loop without the first expression.

Code Snippet:

.....
// initialization of num outside of for loop
int num=1;
for(;num ! = 40 ;num ++) {
   System.out.println("Enter a number: ");
   num = input.nextInt();
}
.....

The code will accept a value for num until the input is 40. This loop does not have any initialization expression. Instead, it has been initialized outside of for loop. The variable num is increased by 1. The loop terminates when num becomes 40. If all the three expressions are left blank, an infinite loop will be created.

The following code demonstrates the use of such loop.

Code Snippet:

.....
for( ; ; ) {
      System.out.println("This will go on and on");
}
.....

The code will print ‘This will go on and on’ unless and until the loop is terminated. break statements can be used to terminate such loops. Such codes lead to infinite loops. Infinite loop makes the program run indefinitely for a long time resulting in the consumption of all resources and stopping the system. Thus, it is a good practice to avoid using such loops in a program.

When the number of user inputs in a program is not known beforehand, an infinite loop can be used in a program where it will wait indefinitely for user input. Thus, when a user input is received, system processes the input and again starts executing the infinite loop.

Nested Loops

The placing of a loop in the body of another loop is called nesting. For example, a while statement can be enclosed within a do-while statement and a for statement can be enclosed within a while statement. When you nest two loops, the outer loop controls the number of times the inner loop is executed. For each iteration of the outer loop, the inner loop will execute all of its iterations.

There can be any number of combinations between the three loops. While all types of loop statements may be nested, the most commonly nested loops are formed by for statements. The following code demonstrates the use of nested-for loop.

Code Snippet:

int i, j;
for (i = 1; i <= 3; i++)
{
   for (j = 1; j <= 2; j++)
   {
      System.out.printf("\n%d %d", i , j );
   }
}

The first for statement is executed first, and the value of ‘i’ is verified to be less than or equal to three, if true, the inner for loop is executed. The inner loop is executed till the condition returns false (in this case, it is run twice) before control is handed back to the outer loop. When the outer loop is run a second time, the value of ‘i’ is incremented, then verified and the inner loop is executed again two times. In this manner, the execution continues till the outer loop’s condition returns ‘false’.

Output:

1 1
1 2
2 1
2 2
3 1
3 2

Comparison

The type of loop that is chosen while writing a program depends on the good programming practice. A loop written using the while statement can also be rewritten using the for statement and vice versa. The do-while statement can be rewritten using the while or the for statement. However, this is not advisable because the do-while statement is executed at least once. When the number of times the statements within the loop should be executed is known, the for statement is used.

The table below lists the differences between while/for and do-while loops.

while/for do-while
Loop is pre-tested. The condition is checked before the statements within the loop are executed. Loop is post-tested. The condition is checked after the statements within the loop are executed.
The loop does not get executed if the condition is not satisfied at the beginning. The loop gets executed at least once even if the condition is not satisfied at the beginning.
Related Post