# Question on "for".

E Ma

Greenhorn

Posts: 1

Nigel Browne

Ranch Hand

Posts: 703

posted 12 years ago

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

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

posted 12 years ago

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.

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