• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Tricky For Loop

 
Vinny Chun
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across a tricky question in the Net.
class Question
{
public static void main(String[] args)
{
int i, j;
for (i=0, j=0; i+j < 20; ++i, j+=i--)
{
System.out.println("i+j = " + (i+j));
}
}
}
What does this program print out?
a.5
b.8
c.13
d.Compile error
Answer a, b and c are correct.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The thing you have to notice here is that i is always 0, and thus the values of j are printed from 0 to 19... That's tricky !
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinny
Were you askig a question or just posting interesting code? On the chance that you were asking a question here is a break down of what happens in this loop.
1st iteration:
i=0, j=0
prints: 'i+j = 0'
2nd iteration:
i=0, j=1
prints: 'i+j = 1'
3rd iteration:
i=0, j=2
prints: 'i+j = 2'
4th iteration:
i=0, j=3
prints: 'i+j = 3'
and so on with i staying 0 and j increasing by 1 each time. This is because in the for loop the increment part: '++i, j+=i--' i is both incremented by one then decremented so it never increases. Meanwhile the expresion for j uses the incremented value of i before it is decremented. The incremented value of i is always 1 so j increases by 1 each time.
If you weren't looking for an explaination then please ignore all of this.

What does this program print out?
a.5
b.8
c.13
d.Compile error
Answer a, b and c are correct.[/B]

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Vinny Chun
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave and Val, thanks for your explanation. I am more clear with this For Loop now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic