C program to print hollow pyramid (Equilateral triangle) star pattern

C program to print hollow pyramid (Equilateral triangle) star pattern

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

Logic to print hollow 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.
  • First inner loop print the space x to (N-1)(where N is the row number and x is the current row number).
  • The second inner loop print the star at xth or last column or for last row. It iterates from 1 to (2*x)-1).

See the, C program to print hollow 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(" ");
        }
        for(y =1; y<=((2*x)-1); ++y)
        {
            //Print star only first and last row col
            if(x==rows || y==1 || y==((2*x)-1))
            {
                printf("*");
            }
            else
            {
                printf(" ");
            }
        }
        // Print new line
        printf("\n");
    }
    return 0;
}

Output:

C program to print hollow pyramid

 

Code Analysis:

It asks the user to enter the row for the hollow 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(" ");
  }

 

The second inner loop print the star at x-th or last column or for the last row otherwise it prints space.

for(y =1; y<=((2*x)-1); ++y)
{
    //Print star only first and last row col
    if(x==rows || y==1 || y==((2*x)-1))
    {
        printf("*");
    }
    else
    {
        printf(" ");
    }
}

 

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

Recommended Post: