JAVA Nested for Loops How will this work for(a=1;a<=5;a++) { for(b=1;b<=a;b++) { System.out.print(b); } System.out.println(); } Please show me the drill at every step?
Well look: for(a=1;a<=5;a++){ for(b=1;b<=a;b++){ System.out.print(b); // Print the value of b } System.out.println(); // Return to line. } Step 1 : a = 1 (a <= 5) --> Yes { Step 1 : b = 1 (b <= 1) --> Yes print(b) // We will print 1. b = b + 1 Step 2 : b = 2 (b <= 1) --> No // Exit the for loop. } Return to line. a = a + 1; The result of this first step will be as follow : 1 {Your cursor is pointing here for a New line} Step 2 : a = 2 (a <= 5) --> Yes { Step 1 : b = 1 (b <= 2) --> Yes print(b) // We will print 1. b = b + 1 Step 2 : b = 2 (b <= 2) --> Yes print(b) // We will print 2. b = b + 1 Step 3 : b = 3 (b <= 2) --> No // Exit the for loop. } Return to line. a = a + 1; The result of the first and second step will be as follow : 1 12 {Your cursor is pointing here for a New line} And so on... so when you finish all your 5 steps, the result will be as follow : 1 12 123 1234 12345 Hope that help you, Good luck.
One syntax detail: a and b were never given a type in your question, so technically the code shouldn't compile. It should be: for( int a = 1; a <= 5; a++ ) { }
She is giving just a part from her program, maybe in the top she declared a and b as intergers.
How will this work for(a=1;a<=5;a++) It won't compile.
Its just a part of the program. a and b are integers. And @ktobah thanks for the help.
@leena1996 You are welcome. @rsmith6559 It will compile well because as I said she already declared a and b in the top as integers.
The question was "How will this work". There's no type declaration, so it won't compile. As you get more experienced troubleshooting, you'll learn to listen closely to the user.
Ok
Join our real-time social learning platform and learn together with your friends!