Cover Image for Pyramid Patterns in C
114 views

Pyramid Patterns in C

Creating pyramid patterns in C involves using nested loops to print a series of characters or numbers in a pattern that resembles a pyramid. Below are examples of two common types of pyramid patterns: one using asterisks (*) and the other using numbers.

  1. Asterisk Pyramid Pattern:

Here’s an example of a C program that prints an asterisk pyramid pattern:

C
#include <stdio.h>

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

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

    for (i = 1; i <= rows; i++) {
        // Print spaces before the asterisks
        for (j = 1; j <= rows - i; j++) {
            printf(" ");
        }

        // Print asterisks
        for (j = 1; j <= 2 * i - 1; j++) {
            printf("*");
        }

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

    return 0;
}

In this program:

  • The user is asked to enter the number of rows for the pyramid.
  • Two nested loops are used to print spaces and asterisks in the desired pattern.
  • The outer loop (i) controls the number of rows, and the inner loops (j) handle spaces and asterisks.
  1. Number Pyramid Pattern:

Here’s an example of a C program that prints a number pyramid pattern:

C
#include <stdio.h>

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

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

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

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

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

    return 0;
}

This program follows a similar structure to the asterisk pyramid example, but instead of printing asterisks, it prints a sequence of numbers in the pyramid pattern.

Compile and run either of these programs, and they will display the respective pyramid pattern based on the number of rows entered by the user.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS