C (programming language)

C program to print inverted pyramid number pattern

Introduction

Let’s explore how to create a C program that generates an inverted pyramid number pattern. We’ll delve into the logic, code structure, and key steps involved in crafting this visually appealing pattern.

Understanding the Pattern

  • Shape: The numbers form an inverted pyramid, with a wide base and a narrow top.
  • Composition: Numbers are used to construct the pyramid, starting from a maximum value and decreasing towards 1.
  • Arrangement: Numbers are arranged in rows, with each row containing one fewer number than the previous row.

Steps to Implement

  1. Include Necessary Header:

C

#include <stdio.h>
  1. Declare Variables:

C

int rows, i, j, num = 1;
  1. Get Input for Number of Rows:

C

printf("Enter the number of rows: ");
scanf("%d", &rows);
  1. Use Nested Loops to Print the Inverted Pyramid:

C

for (i = rows; i >= 1; i--) {
    // Print spaces before numbers in each row
    for (j = 1; j <= rows - i; j++) {
        printf(" ");
    }

    // Print numbers in decreasing order
    for (j = 1; j <= i; j++) {
        printf("%d ", num);
        num++;  // Increment num for the next number
    }

    num = 1;  // Reset num for the next row
    printf("\n");  // Move to the next line
}

Complete Example Code:

C

#include <stdio.h>

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

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for (i = rows; i >= 1; i--) {
        for (j = 1; j <= rows - i; j++) {
            printf(" ");
        }
        for (j = 1; j <= i; j++) {
            printf("%d ", num);
            num++;
        }
        num = 1;  // Reset for the next row
        printf("\n");
    }

    return 0;
}

Explanation

  1. The outer for loop iterates from rows down to 1, controlling the rows of the pyramid.
  2. The first inner for loop prints spaces to create the inverted pyramid shape.
  3. The second inner for loop prints numbers in decreasing order within each row.
  4. num is incremented to generate consecutive numbers, then reset to 1 for the next row.
  5. printf("\n") moves the cursor to the next line after each row.

Key Points to Remember

  • The nested loops control the positioning of numbers and spaces.
  • The num variable keeps track of the current number to print.
  • Adjust the rows variable to control the size of the inverted pyramid pattern.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button