While loop
How while loop works?

Syntax:

Ex:

Example 1: Program to print line 8 times
When you run the program, the output will be:
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.
When you run the program, the output will be:
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,
Problems:
Try all the examples as well as problems with while loop which are mentioned in for loop section.
Last updated
Was this helpful?