+ 3
How to Print like this using Nested for loops in java
1 2 3 2 4 6 3 6 9
13 ответов
+ 6
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.print((j * i)+" ");
}
System.out.println("");
}
+ 2
@Andre Daniel I understand that but I find the nested for loop to print patterns like diamond or pyramid so challenging. I don't know why
+ 2
Any nested for loop will be challenging.
But just go along with the natural flow of code and it should not be hard.
The first for loop (i) will only loop 3 times.
Which means any codes in it will happen 3 times.
And everything inside the loop will have to execute from the start of the loop's '{' to the end of it '}'. (unless interrupted by "break" or "continue"
We notice that inside it contains another for loop (j), which must execute fully again everything inside before moving exiting its loop and continuing the lines of code below it, which is in a previous loop (i).
So when i is 1, it goes through and completes j's loop, printing the value of j * i.
Then when it exits the j forloop, it conrinues on till it des everything in the i forloop, then increments i. See example below.
+ 2
i loop starts
i = 1
j loop starts
j = 1
print j*i //1*1=1
j increments since conditions are not yet met
j = 2
print j*i //2*1=2
j increments since conditions are not yet met
j = 3
print j*i //3*1=3
j conditions are met and loop ends
print new line
i increments since conditions are not yet met
i = 2
j loop starts
j = 1
print j*i //1*2=2
j increments since conditions are not yet met
j = 2
print j*i //2*2=4
j increments since conditions are not yet met
j = 3
print j*i //3*2=6
j conditions are met and loop ends
print empty line
i increments since conditions are not yet met
i = 3
j loop starts
j = 1
print j*i //1*3=3
j increments since conditions are not yet met
j = 2
print j*i //2*3=6
j increments since conditions are not yet met
j = 3
print j*i //3*3=9
j conditions are met and loop ends
print empty line
i conditions are met and loop ends
+ 2
I am confused in Print those result but anyways Thank you so much
+ 2
I recommend familiarizing yourself with the way for loops work. 😊
I simply typed out what the computer sees for the code I typed earlier.
+ 2
okay thank you so much .
+ 1
Thank you I dont undertand yet
+ 1
Check a course to learn how for loops work. After that it's just the language's syntax. But glad to help.
+ 1
Thank you so much
+ 1
Thanks so much @Andre Daniel, the best explanation ever
0
I don't think I could have come up with the (j*i) bit in line 3.