Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

nested for loop not working properly ?

 
Nikhil Sagar
Ranch Hand
Posts: 216
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

output is i=1 j=1
i=1 j=2
the problem is after it should have print i=2 j=1
i=2,j=2
but they dont so i want to know how nested loop is working in this.................
 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, please use code tags and proper indentation when posting code. That makes it much easier to read. I've added the code tags for you here.

You initialize i and j before the loops, and never reinitialize j. So the process is:

i = 1, enter the outer loop
j = 1, enter the inner loop
print i=1, j=1
increment j
j = 2, enter the inner loop again
print i=1,j=2
increment j
j = 3, exit the inner loop
increment i
i = 2, enter the outer loop again
j = 3 (still) bypass inner loop
increment i
i = 3, exit outer loop

 
Nikhil Sagar
Ranch Hand
Posts: 216
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, i missed it, thank you so much Greg.
wonderful explanation.
and sorry for no code tags.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic