Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Question on "for".

E Ma
Greenhorn
Posts: 1
Hello all,there is a program.
I think the answer is 1+2+2+3+3+3+4+4+4+4+5+5+5+5+5=55,but the correct answer is 35.Can anyone tell me why,I,m confused about it.
Thanks a lot.

[ March 23, 2004: Message edited by: E Ma ]

Nigel Browne
Ranch Hand
Posts: 703
Originally posted by E Ma:
Hello all,there is a program.
public class Test{
public static void main(String[] args){
int i,j,s=0;
for(i=1;i<=5;++i)
for(j=1;j<=i;++j)
s+=j;
System.out.println(s);
}
}

In the above code on the first iteration i=1 and j =1 and therefore s = 1.
On to the second iterartion now i =2 but in the first loop of j, j is set back to one and hence j loops twice. So we s+= 1 and s+=2 giving s =4. On to the third, fourth and fifth iterations of the i loop and the same logic applies. So the final sum for s would be :
0+1+1+2+1+2+3+1+2+3+4+1+2+3+4+5 = 35

Hope this explains things for you
Nigel

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
Hi,
Welcome to JavaRanch!
You're adding up the values of j, not i. When i is 1, j will be 1. When i is 2, j will be 1 and 2. When i is 3, j will be 1, 2, and 3, etc -- not 3, 3, and 3 as your expected solution assumes. You'd get the answer you expected if you added up the value of i at every iteration instead of the value of j.

Ravinder S Edhan
Ranch Hand
Posts: 57
Hi ....
First iteration i=1 and j =1, thus s = 1.
Second iterartion now i =2, first loop of j, j = 1 and thus j loops twice. So s+= 1 and s+=2 giving s =4.
and thus iterative process for further loop