Task: Print the Given Pattern
Objective: Use nested for loops to print the given pattern.
![]() |
Print Diamond Shape with Asterisks using Java Loop Pattern Program |
Pattern to Print:
*
* *
* *
* *
* *
* *
* *
* *
*
Detailed Instructions:
- Use an outer for loop to iterate 9 times (representing the rows).
- Inside the outer loop, use an inner for loop to determine the number of spaces and asterisks (*).
- For the upper half (rows 0 to 4), print spaces followed by asterisks and spaces.
- For the lower half (rows 5 to 8), print spaces followed by asterisks and spaces in the reverse order.
- Print a newline character to move to the next row.
Sample Output:
*
* *
* *
* *
* *
* *
* *
* *
*
Java Code:
public class PatternPrinter {
public static void main(String[] args) {
int n = 5; // Half the height of the pattern
// Upper half
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
System.out.print("*");
for (int j = 0; j < 2 * i - 1; j++) {
System.out.print(" ");
}
if (i > 0) {
System.out.print("*");
}
System.out.println();
}
// Lower half
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j < n - i - 1; j++) {
System.out.print(" ");
}
System.out.print("*");
for (int j = 0; j < 2 * i - 1; j++) {
System.out.print(" ");
}
if (i > 0) {
System.out.print("*");
}
System.out.println();
}
}
}