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. The pattern with 5 rows should look like:
    *
   * *
  *   *
 *     *
*********

Required knowledge:

Basic C programming, If else, For loop
Before continuing to this pattern it is recommended to go through how to print equilateral triangle or Pyramid star pattern.

Logic:

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). And here star only gets printed when row=n or column=1 or column= (2*rownumber - 1) (where n is the total number of rows). And 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:

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

#include <stdio.h>

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

    //Reads number of rows to be printed from user
    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 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
X
_
Enter value of n: 5
    *
   * *
  *   *
 *     *
*********


Screenshot:

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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment