Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# may be this is very basic question...........

Ranch Hand
Posts: 50
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?

Ranch Hand
Posts: 348

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.

Ranch Hand
Posts: 281
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:

Ranch Hand
Posts: 50
Thank you very much

Ranch Hand
Posts: 417
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

Gold Digger
Sheriff
Posts: 7610
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

 I am mighty! And this is a mighty small ad: Rocket Oven Kickstarter - from the trailboss https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss