This week's book giveaway is in the NodeJS forum.
We're giving away four copies of Serverless Applications with Node.js and have Slobodan Stojanovic & Aleksandar Simovic on-line!
See this thread for details.
Win a copy of Serverless Applications with Node.js this week in the NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

confusing for Loop.  RSS feed

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will the following code print?

Ans: It will print 10
My question is that the if statement satisfies in the 2 checking loop itself.first
c=0;
i=0,j=0,k=0;--->c=1
i=0,j=0,k=1;---> c=2
here itself k>j i.e 1>0
so the value of c must be 2..
please explain where am i wrong?
Sonir
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the break statement in the most inner loop only stops the most inner loop.
the 2 outer ones will continue again so at the end c is 10.
 
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you put println's inside each for loop & one right after c is incremented you will see this result:
F:\JavaProgs>java Test
i is: 0
j is: 0
k is: 0
c is: 1
k is: 1
c is: 2
j is: 1
k is: 0
c is: 3
k is: 1
c is: 4
k is: 2
c is: 5
i is: 1
j is: 0
k is: 0
c is: 6
k is: 1
c is: 7
j is: 1
k is: 0
c is: 8
k is: 1
c is: 9
k is: 2
c is: 10
10
If you use this to follow the loops thru I think you will get it.....you have to remember that when you break out of a loop to another loop the inner loop variable will be re-initialized when it is hit again. Look at the code & these results & try writing it down in a small chart.....I thikn this will help you see whats up.
[ January 13, 2002: Message edited by: DC Dalton ]
 
when your children are suffering from your punishment, tell your them it will help them write good poetry when they are older. Like this tiny ad:
global solutions you can do in your home or backyard
https://coderanch.com/t/708587/global-solutions-home-backyard
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!