aspose file tools*
The moose likes Beginning Java and the fly likes Question on Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question on "for"." Watch "Question on "for"." New topic
Author

Question on "for".

E Ma
Greenhorn

Joined: Mar 16, 2004
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

Joined: May 15, 2001
Posts: 673
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Ravinder S Edhan
Ranch Hand

Joined: Dec 15, 2003
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
Following are the number added
0+1+1+2+1+2+3+1+2+3+4+1+2+3+4+5 = 35
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question on "for".