Pattern Problem #2
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:
- 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 two nested loops to print the upper and lower halves of the diamond separately.
- The first outer loop runs from 1 to
nprinting the upper half of the diamond. - The second outer loop runs from
n-11 for printing the lower half of the diamond. - The inner loops for both halves are similar.
- The first inner loop prints the required number of spaces before the asterisks.
- The second inner loop prints the asterisks based on the current row number.
- 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:
4Output:
*
***
*****
*******
*****
***
*









