While Loop

While Loops can be used if we need to execute the same set of statements again and again until a condition is met.

For example, if we need to print a statement 5 times, we can use while loop.

Let’s try to understand with an example:

Example:

Let’s try to print the value of variable i against a condition, i.e., to print the value of i only when it’s value is less than or equal to 6.

In the above code, we have a variable, assigned with a value 1. There is a condition in while loop i.e., i <= 6, which means it is checking if the value of i variable is less than or equal to 6.

Only if this condition is met, the value of i is printed.

There is one important expression in the last line, i.e., i = i + 1.

Why this line is added? Assume that this line is not present. What will happen? When the code executes, initially, i is assigned with a value 1 and while loop checks if this value is less than 6, which is true and prints the value of i.

This prints every time and goes in to infinite loop. It will execute continuously.

Infinite Loop:

To stop the execution, we need to add a condition to increment the value of i so that this executes accordingly.

Output:

The output will print the value of i until the condition satisfies ( i.e., until the value of variable i is less than or equal to 6 ) .

Leave a comment

Design a site like this with WordPress.com
Get started