Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Basic Q

 
Pooja K
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the significance of pre & post increment operators in a for loop?
In the following code, both i++ & ++i produce the same result.

class str_1{
public static void main(String args[]){

int i=0;
for(i=0; i<10; i++)
System.out.println("i "+i);
}
}
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a for loop, post and pre increment ops behave the same when the result is not assigned to another variable. You can use one or the other, but first check your company Java stylesheet if available for the recommended one.
Most code I've seen used the post increment operator, but it is just a convention...
Regards
Beno�t
 
Pooja K
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,
Can you please explain the output of the folowing code???

class str_1{
public static void main(String args[]){

int i=0, j=0;

for(i=0,j=0; i +j <10; ++i, j+=++i)
System.out.println("i "+i + "j " + j + " i+j " + (i+j));

System.out.println("Now doing post \n");
i=0; j=0;

for(i=0,j=0; i +j <10; i++, j+=i--)
System.out.println("i "+i + "j " + j + " i+j " + (i+j));

}
}

Thanks in advance,
Pooja
 
umang bhartia
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Pooja,
Well in your eg, if u look then the first for loop will run twice, as the variable i is incremented twice in one loop, os the value would b:
i =0, j=0
i =2, j=2
i =4, j =6 \\ this would not b printed as i+j is = to zero,
while in another for loop, i is first incremented by one and then after assigning the value to j it is again decreased by 1, so the value of j will b increasing by 1 after every loop while i will remain 0.
Hope this is clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic