0

Explain how to print half pyramid of numbers in java

public class Pattern { public static void main(String[] args) { int rows = 5; for(int i = 1; i <= rows; ++i) { for(int j = 1; j <= i; ++j) { System.out.print(j + " "); } System.out.println(); } } } ok I got this code but will someone explain what steps are there during the execution of the loop which resulted into the output??? it would be helpful....

2nd Aug 2019, 8:08 PM
Aquib Shaikh
Aquib Shaikh - avatar
2 Answers
+ 2
the outer loop is the "parent" loop so to speak, the inner loop is executed as a new loop on each pass of the outer loop(setting the value of j to 1 on each pass), on the first iteration i == 1, and j == 1 so the inner loop has met its condition on the first run, which will result in printing ā€œ1 ā€œ, then breaking out of the inner loop and returning to the outerloop in which a new line is printed and i is incremented by 1. so now that i on the outer loop is incremented by 1 making i == 2, the inner loop is executed as a "new" loop as discussed above, so it sets the value of j to 1 (again) and now the condition is 1<=2(j<=i) so this time it will loop twice, resulting in the output of "1 2" and this process is repeated until the outer loop has met its condition of i<=rows I hope that makes sense to you.
2nd Aug 2019, 9:47 PM
Jake
Jake - avatar
2nd Aug 2019, 9:31 PM
voja
voja - avatar