While loop

How while loop works?

Syntax:

Ex:

Example 1: Program to print line 8 times

// Program to print line 8 times

class Loop {
   public static void main(String[] args) {
      
      int i = 1;
	   
      while (i <= 8) {
         System.out.println("Line " + i);
         ++i;
      }
   }
}

When you run the program, the output will be:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8

Notice, ++i; statement inside the while loop. After 8 iterations, variable i will be 9. Then, the test expression i <= 8 is evaluated to false and while loop terminates.

Example 2: Program to find the sum of natural numbers from 1 to 100.

// Program to find the sum of natural numbers from 1 to 100.

class AssignmentOperator {
   public static void main(String[] args) {
      
      int sum = 0, i = 100;
	   
      while (i != 0) {
         sum += i;     // sum = sum + i;
         --i;
      }
	   
      System.out.println("Sum = " + sum);
   }
}

When you run the program, the output will be:

Sum = 5050

Here, the variable sum is initialized to 0 and i is initialized to 100. In each iteration of while loop, variable sum is assigned sum + i, and the value of i is decreased by 1 until i is equal to 0. For better visualization,

1st iteration: sum = 0+100 = 100, i = 99
2nd iteration: sum = 100+99 = 199, i = 98
3rd iteration: sum = 199+98 = 297, i = 97
... .. ...
... .. ...
99th iteration: sum = 5047+2 = 5049, i = 1
100th iteration: sum = 5049+1 = 5050, i = 0

Problems:

Try all the examples as well as problems with while loop which are mentioned in for loop section.

Last updated