Examples of while loops
For Complete YouTube Video: Click Here
In this class, we will understand Examples of while loops.
We have already discussed the concept of a while loop.
The examples we cover are straightforward but tricky while attempting them in competitive exams or placements exams.
Table of Contents
Examples of while loops
Example 1
The image below is example 1 on the while loop.
In the above example, the value of i is -1.
The “i++” in the while loop will confuse us in the exam and make us feel the value of ‘i’ 0.
So we think that 0==0, and we will enter the while loop and print the statement.
But the i++ is post-increment, the value of ‘i’ is -1 and used -1 in the expression, and later the incrementation is done.
We should be cautious while answering such questions.
Example 2
The image below is example 2 on the while loop.
In the while loop, i = 2 is there, which is an assignment operator.
Generally, we think that assignment operators are not allowed in the loops.
But the assignments are allowed.
The output of the assignment expression is the value that is assigned.
In the above case, the output is 2.
Any number other than 0 is “true,” so we will enter into the loop’s body.
If we assign i =0, it will be false, and we don’t enter the loop’s body.