Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Nested for loop

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The result is
0 1 1 1 2 3 3

Hi everyone, i got this code from k&b scjp studyguide, question 12, chapter 5, page 407 self.test questions.

Am struggling to understand the result of this code, can anyone explain the result. I wil greatly appreciate it.













 
Whizlabs Java Support
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Harold Ndou wrote:


let me give explanation for two iterations.

1st Iteration

when j=0 condition for the outer loop is true so it enters into the loop.
In the inner loop when k=0 condition will be true so it enters the loop and it prints value of j which is equal to 0 after that in the if condition j==0 will become true and the inner loop will be terminated.

2nd Iteration

when j=1 condition for the outer loop is true so it enters into the loop.
In the inner loop k=0 condition will be true so it enters the loop and it prints value of j which is equal to 1 after that both if conditions will be false .so k will be incremented and loop runs again and prints j value and similarly for the third iteration it prints j value 1.

try the remeaning Iterations similarly

 
Harold Ndou
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks so much James for your clear explanation.
I did the remaining iterations, now i understand how this result come about.
 
James X Peterson
Whizlabs Java Support
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
welcome Harold:)
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic