C Program to Print Number Pyramid Pattern

Introduction

A number pyramid pattern is a triangular arrangement where the numbers are printed in a pyramid format. This is a common exercise for beginners in C programming, which helps in understanding nested loops and how to manipulate the output format.

Problem Statement

Create a C program that:

  • Accepts the number of rows for the pyramid.
  • Prints a number pyramid pattern.

Example:

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

Solution Steps

  1. Input the Number of Rows: The size determines how many rows the pyramid will have.
  2. Use Nested Loops: The outer loop will handle the number of rows, and the inner loops will handle printing spaces and numbers.
  3. Display the Number Pyramid: Numbers increase in each row starting from 1, and spaces are used to align the pyramid.

C Program

#include <stdio.h>

int main() {
    int i, j, rows;

    // Step 1: Accept the number of rows for the pyramid
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Step 2: Outer loop for the rows
    for (i = 1; i <= rows; i++) {
        // Step 3: Print spaces for alignment
        for (j = i; j < rows; j++) {
            printf(" ");
        }

        // Step 4: Print numbers for each row
        for (j = 1; j <= i; j++) {
            printf("%d ", j);
        }

        // Move to the next line after each row
        printf("\n");
    }

    return 0;
}

Explanation

Step 1: Input Number of Rows

  • The program begins by asking the user for the number of rows for the pyramid.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows will be printed. It runs from 1 to rows.

Step 3: Print Spaces for Alignment

  • The first 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

  • The second inner loop prints numbers starting from 1. The number of numbers printed in each row increases with each subsequent row.

Output Example

For rows = 5, the output will be:

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

For rows = 6, the output will be:

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

Conclusion

This C program prints a number pyramid by using nested loops to print numbers and spaces. The output is aligned to form a pyramid, and the numbers increase with each row. This exercise is useful for practicing loop control and formatting output in C programming.

Comments