Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between the for loops

 
ishmayel vemuru
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi to every one..
This is ishmayel.. I am going to write complete my SCJP soon..

I had the following doubt regrading the for loop can any one help me please.

1. for( int i=0; i<3; i++)
{
System.out.print(i+"--");
}
out put is :: 0--1--2
2. for( int i=0; i<3; ++i)
{
System.out.print(i+"--");
}
out put is :: 0--1--2
I am thing that out put is like this.... :: 1--2

my question is why I am getting the same output in both conditions...
If both loops are the same than what is the difference between the
for( int i=0; i<3; i++) and for( int i=0; i<3; ++i)
I hope any one may help me soon.
Thanks in Advance..
Ishmayel.
 
Nevin kumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
Both are same in this case.Difference between post increment and pre increment is for example if you have x=0,y=0

case 1:
int i=++x; the value of i is 1.
case 2:
int i=x++; the value of i is 0 and after using x,it's value is incremented that is x=1.
 
ishmayel vemuru
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Naveen kumar..
thanks for your response..

I know the difference between the pre and the post increment/decrement
but why here in Both conditions I am getting the same output.
1.for( int i=0; i<3; i++)
2. for( int i=0; i<3; ++i)

Please explain write in detail.
Thanks in Advance..
Ishmayel
 
Neha Agarwal
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The reason is the way the for loop exceutes
1)Variable is intialized and then comparison is done
eg in this case
i will be initialized to 0 and then compared to value 3 ,since it is less than 3 it goes inside loop and prints value

2)After that it goes to increment part and and increases it by 1 and checks the condition again goes to print statement .So the result in both cases remain same
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Neha Java",
Please check your private messages regarding an important administrative matter.
-Ben
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic