C program to print pyramid star pattern or equilateral triangle star pattern

  • Write a program in C to print pyramid star pattern using for loop.
  • Write a C program to print an equilateral triangle star pattern of n rows using loops.
For an equilateral triangle pyramid star pattern of 5 rows. Program's output should be:
    *
   ***
  *****
 *******
*********

Required Knowledge

Algorithm to print pyramid star pattern using loop
In this program, we are printing a pyramid pattern in which ith row contains (2*i - 1) space separated stars.
  • We first take the number of rows in the pattern as input from user using scanf function.
  • One iteration of outer for loop will print a row of pyramid.
  • Inner for loop prints the initial spaces for every line and nested while loop prints (2*r - 1) space separated stars for rth row of pyramid.

C program to print pyramid star pattern

#include<stdio.h>

int main() {
    int i, space, rows, star=0;
    printf("Enter the number of rows\n");
    scanf("%d",&rows);
    
    /* printing one row in every iteration */
    for(i = 1; i <= rows; i++) {
        /* Printing spaces */
        for(space = 1; space <= rows-i; space++) {
           printf(" ");
        }
        /* Printing stars */
        while(star != (2*i - 1)) {
            printf("*");
            star++;;
        }
        star=0;
        /* move to next row */
        printf("\n");
    }

    return 0;
}
Output
Enter the number of rows
6
     *
    ***
   *****
  *******
 *********
***********

C program to print pyramid star pattern using single for loop

#include<stdio.h> 

int main(){
    char *str="*****************";
    int i,j, rows;
    
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
      
    for(i=0;i<rows;i++){
       printf("%*.*s\n",rows+i, 2*i+1, str);
    }
    return 0;
}
Output
Enter the number of rows
6
     *
    ***
   *****
  *******
 *********
***********

Related Topics
C program reversed pyramid star pattern
C program hollow pyramid star pattern
C program hollow diamond star pattern
C program right triangle star pattern
C program hollow square star pattern
C program heart shape star pattern
C program natural number triangle pattern
C program palindrome triangle pattern
C program same row element triangle pattern
List of all C pattern programs