Java Program to Print Downward Right Triangle Number Pattern - 3
In this program we print a downward right triangle number pattern in which every row ends with the same number. The first row prints 1 to 5, the second starts at 2, the third at 3, and so on until the last row prints just 5.
Like every pattern program, it is built from nested loops: the outer loop picks the row, and the inner loop prints what goes on that row.
1. The Pattern
For 5 rows the program prints:
Pattern
1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
2. How the Program Works
Here is what each printed line is made of when numberOfRows is 5:
| Line | Value of row | Numbers printed | Printed |
|---|---|---|---|
| 1 | 1 | from 1 to 5 | 1 2 3 4 5 |
| 2 | 2 | from 2 to 5 | 2 3 4 5 |
| 3 | 3 | from 3 to 5 | 3 4 5 |
| 4 | 4 | from 4 to 5 | 4 5 |
| 5 | 5 | from 5 to 5 | 5 |
- The outer loop counts
rowup from 1 tonumberOfRows. - The inner loop starts
columnatrowinstead of 1 and runs up tonumberOfRows, printingcolumnfollowed by a space. Because the start moves one place right on every row while the end stays fixed, each row is one number shorter. - Compare this with Number Pattern - 7, where the end of each row moves (1 to 5, 1 to 4, …) and the start stays at 1.
System.out.println()moves to the next line after each row.
3. Java Program
public class Pattern9 {
public static void main(String[] args) {
int numberOfRows = 5;
// outer loop for the rows
for (int row = 1; row <= numberOfRows; row++) {
// inner loop prints the numbers from row up to numberOfRows
for (int column = row; column <= numberOfRows; column++) {
System.out.print(column + " ");
}
// move to the next line
System.out.println();
}
}
}
Output
1 2 3 4 5 2 3 4 5 3 4 5 4 5 5
4. Print the Pattern for Any Number of Rows
To let the user choose the size of the pattern, read the number of rows with a Scanner. The loops stay the same.
import java.util.Scanner;
public class Pattern9Input {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int numberOfRows = scanner.nextInt();
scanner.close();
// outer loop for the rows
for (int row = 1; row <= numberOfRows; row++) {
// inner loop prints the numbers from row up to numberOfRows
for (int column = row; column <= numberOfRows; column++) {
System.out.print(column + " ");
}
// move to the next line
System.out.println();
}
}
}
Output (with sample input)
Enter the number of rows: 6 1 2 3 4 5 6 2 3 4 5 6 3 4 5 6 4 5 6 5 6 6
5. Summary
- The outer loop picks the row; the inner loop prints the numbers for that row.
- Starting the inner loop at
rowmakes each row begin one number later, while every row still ends atnumberOfRows. - Keep
numberOfRowsin a variable, so the same program can print the pattern in any size.
Related Programs
Was this tutorial helpful?