Java Program to Print a Number Pyramid

Introduction

Printing patterns like pyramids using numbers is a common programming exercise. It helps one understand nested loops and how to control the flow of output. In this guide, we will write a Java program to print a number pyramid pattern.

Problem Statement

Create a Java program that:

  • Accepts a size as input.
  • Prints a pyramid of numbers.

Example:

  • Input: size = 5
  • Output:
        1
       1 2
      1 2 3
     1 2 3 4
    1 2 3 4 5
    

Solution Steps

  1. Define the Number of Rows: Based on the size input, determine how many rows the pyramid will have.
  2. Use Nested Loops: Use nested loops to print the numbers and spaces to form the pyramid shape.
  3. Display the Pyramid: Print the number pyramid pattern on the console.

Java Program

// Java Program to Print a Number Pyramid
// Author: [Your Name]

import java.util.Scanner;

public class NumberPyramid {
    public static void main(String[] args) {
        // Step 1: Accept the size input from the user
        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 the left pyramid alignment
            for (int j = i; j < size; j++) {
                System.out.print(" ");
            }

            // Step 4: Print numbers for each row
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }

            // Step 5: Move to the next line after each row is printed
            System.out.println();
        }

        // Closing the scanner object to avoid memory leaks
        sc.close();
    }
}

Explanation

Step 1: Input Size

  • The program begins by taking input for the pyramid size using a Scanner object.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows of the pyramid will be printed based on the size input.

Step 3: Print Spaces for Alignment

  • The inner loop prints spaces to align the numbers in a pyramid shape. The number of spaces decreases as you move down the rows.

Step 4: Print Numbers

  • Another inner loop prints numbers starting from 1 up to the current row number. The numbers are separated by spaces to maintain pyramid shape.

Step 5: Print a New Line

  • After printing each row, the program moves to the next line for the next row of the pyramid.

Output Example

For size = 5, the output is:

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

For size = 7, the output is:

      1
     1 2
    1 2 3
   1 2 3 4
  1 2 3 4 5
 1 2 3 4 5 6
1 2 3 4 5 6 7

Conclusion

This program demonstrates how to print a number pyramid using nested loops in Java. By manipulating the number of spaces and numbers printed on each row, the pyramid shape is achieved. This exercise is useful for practicing control flow and loop structures in Java.

Comments