Sitemap

Pattern Problem #2

2 min readFeb 24, 2023

--

Write a Java program that takes an integer n as input from the user and prints a diamond pattern using asterisks. The diamond pattern should have n rows, where the first and last rows have one asterisk each, and each subsequent row has two more asterisks than the previous row until reaching the middle row. The middle row has 2n-1 asterisks. The program should print the upper half of the diamond pattern first, then print the lower half of the diamond pattern in reverse order. Each row should be preceded by the appropriate number of spaces so that the asterisks are centred.

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 upper half of diamond
for (int i = 1; i <= n; i++) {
// Loop for printing spaces
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// Loop for printing asterisks
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}

// Loop for lower half of diamond
for (int i = n - 1; i >= 1; i--) {
// Loop for printing spaces
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// Loop for printing asterisks
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
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 two nested loops to print the upper and lower halves of the diamond separately.
  5. The first outer loop runs from 1 to n printing the upper half of the diamond.
  6. The second outer loop runs from n-1 1 for printing the lower half of the diamond.
  7. The inner loops for both halves are similar.
  8. The first inner loop prints the required number of spaces before the asterisks.
  9. The second inner loop prints the asterisks based on the current row number.
  10. We print a new line after printing all the characters in a row.

Example:

Get Pankaj Yadav’s stories in your inbox

Join Medium for free to get updates from this writer.

Input:

4

Output:

    *
***
*****
*******
*****
***
*

Pankaj

--

--

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!