Skip to content

Latest commit

 

History

History
75 lines (75 loc) · 2.68 KB

while.md

File metadata and controls

75 lines (75 loc) · 2.68 KB

While loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

while (boolean_condition)
{
// some statements here
}

Here, statement(s) may be a single statement or a block of statements. The boolean condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.

Ex.

i = 1
while(i < 6)
{
print(i)
i = i+1
}

Output:

1 2 3 4 5

Flow Diagram:


While loop in C

#include
int main()
{
int count=1;
while (count <= 4)
{
printf("%d ", count);
count++;
}
return 0;
}

Output:

1 2 3 4

While loop in Python

count=1
while(count<=4):
print(count)
count=count+1

Output:

1 2 3 4

Explanation:


Step 1: The variable count is initialized with value 1 and then it has been tested for the condition.
Step 2: If the condition returns true then the statements inside the body of while loop are executed else control comes out of the loop.
Step 3: The value of count is incremented using ++ operator then it has been tested again for the loop condition.

Now, consider this loop:

i = 1
while(i < 6)
{
print(i)
}
This is what is known as an infinite loop, or never ending loop, meaning this loop never finishes running. This is because the value of i is not changing, it is always =1, so the condition that i<6 will always be true. Hence here 1 will be printed indefinitely.

While with else


Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such a case, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.

Ex.

counter = 0

while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")

Output:

Inside loop
Inside loop
Inside loop
Inside else