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

Write a C program to print hollow pyramid or hollow equilateral triangle star(*) pattern series using for loop. How to print hollow pyramid star pattern series using for loop in C programming. Logic to print hollow pyramid star pattern series in C program.

Example

Input

Input rows: 5

Output

Required knowledge

Basic C programming, If else, For loop

Must know - Program to print pyramid star pattern

Logic to print hollow pyramid star pattern

At first glance the pattern may seem to be difficult but trust me if you are done with simple pyramid star pattern then there won't be much difficulty doing this. To make this pattern easy first of all lets ignore the trailing spaces. If you ignore the trailing spaces the pattern would look like:

which is a normal hollow equilateral triangle star pattern. Here each row contains total 2*rownumber - 1 characters (including both inside spaces and stars). Here star only gets printed when row=n or column=1 or column= (2*rownumber - 1) (where n is the total number of rows). Inside spaces gets printed when stars don't.

Now, printing trailing spaces isn't difficult we just need to print n - rownumber spaces per row (where n is the total number of rows to be printed).

Program to print hollow pyramid star pattern

/**
 * C program to print hollow pyramid triangle star pattern
 */

#include <stdio.h>

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

    // Input rows to print from user
    printf("Enter number of rows : ");
    scanf("%d", &n);

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

        // Print hollow pyramid
        for(j=1; j<=(2*i-1); j++)
        {
            if(i==n || j==1 || j==(2*i-1))
            {
                printf("*");
            }
            else
            {
                printf(" ");
            }
        }

        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5
    *
   * *
  *   *
 *     *
*********

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>