+ 1

Can someone help me

int x=1; for (;x<6;x++) x*=x; System.out.printf("%d",x);

9th Feb 2018, 2:53 PM
Robert Mili
11 Answers
+ 4
Yup. You'll always get 26 from that code. Only way you'll get another number is if you make the condition < 5 or > 26 It checks the loop condition FIRST and then it runs the code. It doesn't check if the loop should stop or continue until it checks the loop condition again in the next loop through. During the second loop through, the result is 5 when it goes into the next loop through. You're using multiplication inside of your loop, so that makes x 25 before the end of that loop through. The X++ in the condition causes the 25 to increase by one after the calculation, which makes it 26. When it checks the condition at that point, it sees that it's greater than 15 and stops the loop, thus the end result is 26. Get it now?
9th Feb 2018, 3:22 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 14
after loop1) x=1*1 + 1 = 2 after loop2)x=2×2 + 1 =5 after loop3)x=5×5 + 1 = 26 //condition becomes false now
9th Feb 2018, 2:57 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 4
Best of luck to you Robert!
9th Feb 2018, 3:07 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 4
You're more than welcome bro. Hope that helps.
9th Feb 2018, 3:30 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 3
When in doubt, throw in some print statements so you can see the flow and values of your variables. It'll help you trace things and better understand what's happening to generate end results. int x=1; for (;x<6;x++) { System.out.println("Loop through: X = " + x); x*=x; } System.out.printf("Final result: X = %d",x);
9th Feb 2018, 3:06 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 3
thank you so much for helping me
9th Feb 2018, 3:25 PM
Robert Mili
+ 2
that i will gona do from now, thank you for helping me
9th Feb 2018, 3:05 PM
Robert Mili
+ 2
int x=1; for (;x<15;x++) x*=x; System.out.printf("%d",x);
9th Feb 2018, 3:12 PM
Robert Mili
+ 2
i get agein 26 :(
9th Feb 2018, 3:12 PM
Robert Mili
+ 1
Can someone explain me how will output 26.
9th Feb 2018, 2:53 PM
Robert Mili
+ 1
aha now i get it, thank you alot
9th Feb 2018, 2:58 PM
Robert Mili