Happy to Announce Our New Discussion Forum | Join Now

Print statement inside for loop

Could someone explain how a “print” statement works in an update part of a “for loop”, like this:
for(int x = 0; x<i.length; System.out.print(i[x]))x++;

Thanks.

Hi,
Execution is similar like normal for loop execution. I am changing your for loop a bit.

for( int x = 0; x < 3 ; sop(x) ) {
x ++;
}

Iteration 1
x is 0 . x < 3 => 0 < 3 => true. As condition is true, control goes into for loop body . x will be incremented by 1 due to x ++. Now x is 1. Control goes increment/decrement part of for loop it prints x value.
Output so far
1
Iteration 2
x is 1 . x < 3 => 1 < 3 => true. As condition is true, control goes into for loop body . x will be incremented by 1 due to x ++. Now x is 2. Control goes increment/decrement part of for loop it prints x value.
Output so far
12
Iteration 3
x is 2 . x < 3 => 2< 3 => true. As condition is true, control goes into for loop body . x will be incremented by 1 due to x ++. Now x is 3. Control goes increment/decrement part of for loop it prints x value.
Output so far
123
Now x is 3, 3<3 => false. As condition is false for loop stops execution.
Output
123

I hope the above information clarifies your query. Please let me know if there are any issues.

Thanks and Regards
Narayana B | OCAJP 8 Certified
Whizlabs Team | www.whizlabs.com

2 Likes

It’s clear now with your explanation.
Thank you very much.