Sitemap

Pattern Problem #1

2 min readFeb 24, 2023

--

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:

  1. First, we import the Scanner class to get user input.
  2. We create a Scanner object sc to get input from the user.
  3. We read an integer n from the user using the nextInt() method of the Scanner class.
  4. We use a nested loop to print the required pattern.
  5. The outer loop runs from 1 to n for printing n rows.
  6. The inner loop runs from 1 to i for printing i columns in each row.
  7. We print the column number followed by a space using the print() method.
  8. 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:

5

Output:

1 
1 2
1 2 3
1 2 3 4
1 2 3 4 5

--

--

Pankaj Yadav
Pankaj Yadav

Written by Pankaj Yadav

Do I know it all? Nope! But I love uncovering the 'why' behind tech and business stories. Stick with me, we’ll explore together! Stick around, folks!