+ 1
Can someone help me
int x=1; for (;x<6;x++) x*=x; System.out.printf("%d",x);
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?
+ 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
+ 4
Best of luck to you Robert!
+ 4
You're more than welcome bro. Hope that helps.
+ 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);
+ 3
thank you so much for helping me
+ 2
that i will gona do from now, thank you for helping me
+ 2
int x=1;
for (;x<15;x++)
x*=x;
System.out.printf("%d",x);
+ 2
i get agein 26 :(
+ 1
Can someone explain me how will output 26.
+ 1
aha now i get it, thank you alot