Pattern Problem #1
Write a Java program that takes an integer n as input from the user and prints a pattern of numbers in the form of a right triangle. In each row, the program should print the numbers from 1 to the row number separated by spaces. The first row should contain the number 1, the second row should contain the numbers 1 and 2, the third row should contain the numbers 1, 2, and 3, and so on, up n rows.
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// Loop for printing rows
for (int i = 1; i <= n; i++) {
// Loop for printing columns
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}Explanation:
- First, we import the Scanner class to get user input.
- We create a Scanner object
scto get input from the user. - We read an integer
nfrom the user using thenextInt()method of the Scanner class. - We use a nested loop to print the required pattern.
- The outer loop runs from 1 to
nfor printingnrows. - The inner loop runs from 1 to
ifor printingicolumns in each row. - We print the column number followed by a space using the
print()method. - After printing all the columns in a row, we move to the next line using the
println()method.
Example:
Get Pankaj Yadav’s stories in your inbox
Join Medium for free to get updates from this writer.
Input:
5Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5









