C program to print a pattern of a equilateral triangle using star

C program to print pyramid star pattern/equilateral star pattern

In this article, I will show you, How to write a C program to print pyramid star pattern or equilateral triangle star pattern series of n rows using for loop. How to print pyramid star pattern in C programming. Here, one thing is important to know that the rows of the triangle.

Logic to print pyramid star pattern ( equilateral triangle star pattern)

  • Enter the row value for the equilateral triangle.
  • Here I have used three loops one is the outer loop to change the line and two inner loops to print star and space.
  • The outer loop iterate row times and print a newline after completing the inner loop.
  • If you will look at the design carefully,  then you will find that the N rows pyramid contains (2*x)-1) star and (N-x)  spaces (where N is the row number and x is the current row number).
  • So to print the space inner loop iterate x to N times and to print the star second inner loop iterate 1 to (2*x)-1) times.

See the, C program to print pyramid star pattern:

 

#include <stdio.h>

int main()
{
    int x = 0,y = 0;
    unsigned int rows = 0;

    printf("Enter the number of rows = ");
    scanf("%u",&rows);

    for(x=1; x<=rows; ++x)
    {
        // Print spaces
        for(y=x; y<=rows; ++y)
        {
            printf(" ");
        }

        // Print star/
        for(y =1; y<=((2*x)-1); ++y)
        {
            printf("*");
        }
        // Print new line
        printf("\n");
    }
    return 0;
}

Output:

print a pattern of a equilateral triangle using star in c

 

Code Analysis:

It asks the user to enter the row for the pyramid (equilateral triangle).

printf("Enter the number of rows = ");
scanf("%u",&rows);

 

first, inner loop print space x to (N-1) times.

// Print spaces
for(y=x; y<rows; ++y)
{
    printf(" ");
}

 

Second inner loop print star and it will iterate 1 to (2x-1) times.

// Print star
for(y =1; y<=((2*x)-1); ++y)
{
    printf("*");
}

The outer loop print the newline after each iteration of the inner loops.

Recommended Post: