Print inverted half pyramid as shown:
1111
222
33
4
My code is:
public class HW5 {
//5. Print Inverted Half Pyramid.
public static void main(String[] args) {
int n = 4;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}
}
}
Above code gives following output:
4444
333
22
1
How do I print the required output as shown above?
You need to swap the for
loops. The outer loop is the number to print and the inner loop is the number of times to print it.
public class HW5 {
public static void main(String[] args) {
int n = 4;
for (int j = 1; j <= n ; j++ ) {
for (int i = n - j + 1; i >= 1; i--) {
System.out.print(j);
}
System.out.println();
}
}
}
Above code gives following output:
1111
222
33
4