Introduction
Printing a pyramid pattern is a common exercise in programming. The pattern consists of rows of stars (*
), where the number of stars increases as you go down each row, and spaces are used for alignment to make it symmetrical.
Problem Statement
Create a Java program that:
- Accepts the size of the pyramid.
- Prints a pyramid using stars (
*
).
Example:
- Input:
size = 5
- Output:
* *** ***** ******* *********
Solution Steps
- Input the Size of the Pyramid: The size determines the number of rows in the pyramid.
- Use Nested Loops: The outer loop will control the number of rows, and inner loops will handle printing the spaces and stars.
- Display the Pyramid: Print stars and spaces for each row to form the pyramid shape.
Java Program
// Java Program to Print a Pyramid
// Author: [Your Name]
import java.util.Scanner;
public class PyramidPattern {
public static void main(String[] args) {
// Step 1: Accept the size of the pyramid
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the pyramid: ");
int size = sc.nextInt();
// Step 2: Outer loop for the rows
for (int i = 1; i <= size; i++) {
// Step 3: Print spaces for alignment
for (int j = i; j < size; j++) {
System.out.print(" ");
}
// Step 4: Print stars in each row
for (int k = 1; k <= (2 * i - 1); k++) {
System.out.print("*");
}
// Move to the next line after printing each row
System.out.println();
}
// Closing the scanner object
sc.close();
}
}
Explanation
Step 1: Input Size
- The program begins by taking input for the size of the pyramid from the user using a
Scanner
object. This size determines how many rows the pyramid will have.
Step 2: Outer Loop for Rows
- The outer loop controls how many rows are printed, from 1 up to the size entered by the user.
Step 3: Print Spaces for Alignment
- The first inner loop prints spaces. The number of spaces is based on the current row number, and decreases as you move down the pyramid, ensuring proper alignment of stars.
Step 4: Print Stars
- The second inner loop prints stars. The number of stars follows the formula
2 * i - 1
, wherei
is the current row number. This ensures that the number of stars increases by 2 in each subsequent row.
Output Example
For size = 5
, the output will be:
*
***
*****
*******
*********
For size = 6
, the output will be:
*
***
*****
*******
*********
***********
Conclusion
This Java program prints a pyramid using stars (*
). The number of stars increases as you move down the rows, while spaces are used to center the stars, forming a symmetrical pyramid. This exercise is a great way to practice working with loops and formatting output in Java.
Comments
Post a Comment
Leave Comment