C program to print Equilateral triangle (Pyramid) star pattern

Write a C program to print the equilateral triangle or Pyramid star(*) pattern series of n rows using for loop. How to print Pyramid star pattern series using for loop in C programming. The pattern of 5 rows should look like:
    *
   ***
  *****
 *******
*********

Required knowledge:

Basic C programming, For loop

Logic:

There can be many ways of thinking of the problem here I am discussing the easiest one. Here we need to print two things one is the trialing spaces and other is the equilateral triangle. As like other star pattern problems here also spaces are arranged in a special way i.e. each row contains n - row_number spaces (where n is the total number of rows).

When you look to the total number of stars(*) in the equilateral triangle pattern you will notice that each row contains 2*rownumber - 1 stars.

Program:

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

#include <stdio.h>

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

    //Reads number of rows to be printed
    printf("Enter value of n : ");
    scanf("%d", &n);

    for(i=1; i<=n; i++)
    { 
        //Prints trailing spaces
        for(j=i; j<n; j++)
        {
            printf(" ");
        }

        //Prints the pyramid pattern
        for(j=1; j<=(2*i-1); j++)
        {
            printf("*");
        }

        printf("\n");
    }

    return 0;
} 


Output
X
_
Enter value of n: 5
    *
   ***
  *****
 *******
*********


Screenshot:

Equilateral triangle star pattern program in C

Happy coding ;)


Labels: , , ,