C Program to Print Palindrome Pyramid Pattern

Introduction

A palindrome pyramid pattern consists of numbers arranged in such a way that they form a mirrored sequence, making each row a palindrome. The numbers increase from 1 to the current row number, and then decrease back to 1. This exercise helps in practicing nested loops and number manipulation.

Problem Statement

Create a C program that:

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

Example:

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

Solution Steps

  1. Input the Number of Rows: The user defines how many rows the pyramid should have.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loops handle printing spaces and the palindrome numbers.
  3. Display the Palindrome Pyramid: Print numbers increasing from 1 up to the row number and then decrease back to 1.

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 rows
    for (i = 1; i <= rows; i++) {
        // Step 3: Print spaces for alignment
        for (j = i; j < rows; j++) {
            printf(" ");
        }

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

        // Step 5: Print decreasing numbers
        for (j = i - 1; j >= 1; j--) {
            printf("%d", j);
        }

        // Move to the next line after printing 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 palindrome pyramid.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed, running from 1 to rows.

Step 3: Print Spaces for Alignment

  • The inner loop prints spaces before the numbers to align the pyramid in the center.

Step 4: Print Increasing Numbers

  • The second inner loop prints numbers in increasing order from 1 to the current row number (i).

Step 5: Print Decreasing Numbers

  • The third inner loop prints numbers in decreasing order starting from i - 1 down to 1.

Output Example

For rows = 5, the output will be:

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

For rows = 4, the output will be:

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

Conclusion

This C program prints a palindrome pyramid pattern by using nested loops to print numbers in increasing and decreasing order. The spaces before the numbers ensure proper alignment to create the pyramid shape. This exercise helps in practicing loop control, number manipulation, and formatting output in C programming.

Comments