The While loop can execute a set of commands till the condition is true
While Loops are also called conditional loops.
Once the condition is met then the loop is finished.
Let’s now see a few examples:
Example 1 – Print number from 1 to 15
Here, if we want to derive the loop from this scenario, we have the following conditions:
Condition: Write from 1 to 15
And the decision we are deriving is:
Decision: Have we reached 15
Based on this we can write the below pseudocode:
y = 0
while y < 15
y+=1
print(y)
Example 2 - Print a statement 3 times using while loop.
Condition: Till the time the test expression remains true we will run the body of while loop
And the decision we are deriving is:
Decision: Have we printed the statement 3 times
Based on this we can write the below pseudocode:
y = 0
while y < 3
y+=1
print(“I will eat healthy food every day.”)
This is the result for the code
I will eat healthy food every day.
I will eat healthy food every day.
I will eat healthy food every day.
Example 3 - Print a statement 3 times after that print different statement.
Condition: Till the time the test expression remains true we will run the body of while loop printing statement 1 and after the condition is false, we will print statement 2.
And the decision we are deriving is:
Decision: Have we printed the statement 1 three times, if yes then print the statement 2
Based on this we can write the below pseudocode:
y = 0
while y < 3
y+=1
print(“Please,”)
else
print(“I want to play.”)
This is the result for the code
Please,
Please,
Please,
I want to play.
Example 4 - Print number from 10 to 1
Condition: Till the time the test expression remains true we will run the body of while loop printing statement and after the condition is false the loop will stop
And the decision we are deriving is:
Decision: Have we printed 1
Based on this we can write the below pseudocode:
x = 10
while x==1
print(x)
x-=1
This is the result for the code
10
9
8
7
6
5
4
3
2
1