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:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Bear Bibeault
• Junilu Lacar
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• salvin francis
• Frits Walraven
Bartenders:
• Scott Selikoff
• Piet Souris
• Carey Brown

# sun's sample ques

Ranch Hand
Posts: 114
i am not able to get the following ques.
public class test{
public static void main(String args[]){
int m=2;
int p=1;
int t=0;
for(;p<5;p++){<br /> if(T++>m){
m=p+t;
}
}
System.out.println("t="+t);
}
}
how t=4?
i thought t=3,because in the first iteration of for loop
t=1 and if(test) fails so next iteration takes place.
if()increments t to 2.and again t++<m>
third iteration makes t=3

Ranch Hand
Posts: 44
Hi Nachiket.
Remember: the value of t is returned, compared and then incremented, so your If statement with the t++ in works like this:
condition = t>m;
t = t+1;
if(condition) {m = p + t;}
It ends up as 4.
Hope it makes sense to you.
Francisco.

Ranch Hand
Posts: 117

Originally posted by nachiket deshpande:
i am not able to get the following ques.
public class test{
public static void main(String args[]){
int m=2;
int p=1;
int t=0;
for(;p<5;p++){<br /> if(T++>m){
m=p+t;
}
}
System.out.println("t="+t);
}
}
how t=4?
i thought t=3,because in the first iteration of for loop
t=1 and if(test) fails so next iteration takes place.
if()increments t to 2.and again t++<m<br /> third iteration makes t=3<br /> and inner if(){} exits.so final value of t should be 3 not 4.please help.

<br /> Hi,<br /> If you take a look at the if (t++ > m) statement, post-increment operator is used => hence the first value of t using in the test is 0 not 1. So here goes the iteration:
1. m = 2, p = 1, t = 0 (test value), t = 1 (post-increment value)
2. m = 2, p = 2, t = 1 (test value), t = 2 (p-i value)
3. m = 2, p = 3, t = 2 (test value), t = 3 (p-i value)
4. m = 2, p = 4, t = 3 (test value), t = 4 (p-i value), m = 4 + 2 = 6
5. m = 6, p = 5 => out of the loop => final value of t is 4.

Regards,
Lam

Ranch Hand
Posts: 18944
Hi Nachiket,
I took the sample questions too, yesterday. =)
By inserting a println like,
for(;p<5;p++){<br /> System.out.println("p="+ p + " t="+t + " m="+m);<br /> if(t++>m){
m=p+t;
}
}
You'll get this result :
p=1 t=0 m=2
p=2 t=1 m=2
p=3 t=2 m=2
p=4 t=3 m=2
t=4
P has incremented to 5 afer the last statement of the for loop has executed, and before the p<5 comparison. The same is true for t, it has incremented before the loop exits.
- Emerald -

nachiket deshpande
Ranch Hand
Posts: 114
Thank you all!