In Do ... while loop, why the output is not as per while condition | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In Do ... while loop, why the output is not as per while condition

blic class Program { public static void main(String[] args) { int x = 1; do { System.out.println(x*x); x++; } while(x <5); } } //Output is 1,4,9,16 ... this should be 1,4 as pr while condition x<5... am I wrong??? Please respond quickly

4th Oct 2019, 7:48 AM
Tahir Amin
Tahir Amin - avatar
3 Answers
+ 2
Tahir Amin in do while loop, first we do the operation then check the condition. So here we are first printing the value then incrementing the value of x by 1 so after printing 1*1=1 the value of x will be 2. Now we will check condition which is (2 < 5) true. Then again we will go to print 2*2 = 4. And so on... Finally when x = 5, then the condition (5 < 5) will not satisfy and it will not print the next value. Now Here operation will be stop. So the conclusion is that first we do the operation and then check the condition. If condition is true then again do the operation untill the condition in while loop doesn't give false value.
4th Oct 2019, 12:45 PM
A͢J
A͢J - avatar
+ 1
There is no problem in this program. You are incrementing the value of x. First time it will print 1 then increment the value of x by 1. So next time x will be 2 and will print 4. Again x will be 3 and will print 9 and so on till the condition satisfy in while loop.
4th Oct 2019, 8:21 AM
A͢J
A͢J - avatar
0
Then where is the while condition implemented? While x<5 ?. What about this
4th Oct 2019, 11:03 AM
Tahir Amin
Tahir Amin - avatar