• Post Reply Bookmark Topic Watch Topic
  • New Topic

may be this is very basic question...........  RSS feed

 
Raji Addepalli
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class TeSet {
public static void main(String args[]) {
int m = 2;
int p = 1;
int t = 0;
for(;p < 5;p++) {
if(t++ > m) {
m = p + t;
}
}
System.out.println("t equals " + t);
}
}
for this output is t equals 4.
Can any body explain how it is?
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Raji Addepalli:
public class TeSet {
public static void main(String args[]) {
int m = 2;
int p = 1;
int t = 0;
for(;p < 5;p++) {
if(t++ > m) {
m = p + t;
}
}
System.out.println("t equals " + t);
}
}
for this output is t equals 4.
Can any body explain how it is?

Raji,
This Qs put some variable statement here & there to blur your sight, actually if you look more closely, you will see, we are asked to predict the value of t.
And inside the code, the only place t will get updated is "t++" in if (t++>m), since this if statement is part a for loop that will repaet 4 times. p=1,2,3,4.
t++ encounted 4 times, so t =4.
 
Rick Reumann
Ranch Hand
Posts: 281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If all you are concerned with is t simplify the problem and just put in some System.out.prints to see what is going on:


You'll see the following output:
 
Raji Addepalli
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much
 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what will be the initialization value for p ?
for(;p < 5;p++)
is the initialization value optional ?
there are three things needed for for( )

initialization
condition
increment
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mark,
initialization is not mandatory in a for-loop
provided it has been done already, which is the case here with the statement
int p=1;
above the for-loop...
HIH
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!