C Program to Print a Number Pyramid

1. Introduction

Number pyramids are a fascinating way to display numbers in a structured and visually appealing manner. In this tutorial, we will develop a C program to print a number pyramid. This pattern is excellent for practicing nested loops and understanding how to manipulate them to achieve desired outputs in programming.

2. Program Steps

1. Ask the user to enter the number of rows for the pyramid.

2. Use nested loops: one to handle the rows, another to print spaces for alignment, and a third to print the numbers in a pyramid format.

3. Increase the number of printed numbers in each subsequent row.

3. Code Program

#include <stdio.h>

int main() {
    int rows, i, j, num = 1, gap;

    // Prompting user input for the number of rows
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    gap = rows - 1;

    for(i = 1; i <= rows; i++) {
        // Loop for printing spaces
        for(j = 1; j <= gap; j++) {
            printf(" ");
        }
        gap--;

        // Loop for printing numbers
        for(j = 1; j <= 2*i-1; j++) {
            printf("%d", num);
        }
        printf("\n");
        num++;
    }

    return 0;
}

Output:

Enter the number of rows: 5
    1
   222
  33333
 4444444
555555555

Explanation:

1. The program includes the stdio.h header for standard input and output functions.

2. In the main function, variables rows, i, j, num (for numbering), and gap (for managing spaces) are declared.

3. The user is prompted to enter the number of rows for the pyramid.

4. gap is initialized to rows - 1, which will help in printing the leading spaces to form the pyramid shape.

5. A for loop iterates over each row. Inside this loop, another loop prints the required number of spaces to align the numbers properly.

6. After printing spaces, another loop prints numbers incrementally, with the number of digits in each row starting from 1 and increasing by 2 with each subsequent row (to form the pyramid shape).

7. The num variable is incremented after each row is printed, ensuring that each row has a consistent number that increases with each row.

8. The program ends by printing a newline character after completing each row's number sequence, and return 0; indicates successful execution.


Comments