• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for loop

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
class method
{public static void main(String a[])
{int num[] ={1,2,3,4};
for (int i = 0;i < num.length;++i)
System.out.println(num[i]);
}
}
The o/P;1,2,3,4.
But shouldnt it be 2,3,4.Since for every iteration first i is incremented by 1 and other statements are executed.IF for statement is replaced by
for(int i = 0; i < num.length; i++)
the o/p is same.
Anyone pl. explain me how is the program working?
Thanks!

[This message has been edited by Jim Yingst (edited August 03, 2000).]
[This message has been edited by avn (edited August 03, 2000).]
 
mita
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I think the given answer is correct.The iteration part executes after the first execution of the loop.So it starts with i = 0 here.
Hope I made it clear.
Mita
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
when the program executes the for loop first time it takes initilization value ,executes conditional expression and then if true enters the for loop ,the lost incremental expression ++i (i++) will be executed after every time body of the if loop completes.So i++ or ++i doesnot make difference out here .
now traverse the loop u will get 1,2,3,4
i hope this explanation helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic