C program to print hollow inverted pyramid star pattern

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

Required knowledge:

Basic C programming, If else, For loop
Before moving on to this pattern you must be done with how to print inverted pyramid pattern and hollow pyramid patterns as both are recommended before this pattern.

Logic:

If you look to the pattern structure you will notice that you have to do two things with this pattern. First is you have to print a simple inverted pyramid and second is you have to make the inverted pyramid hollow. Printing inverted pyramid won't be difficult as I discussed in my previous post. And to make pyramid hollow you just have to apply a condition before printing stars i.e. print stars only when row=1 or column=1 or column=(2*rownumber - 1) otherwise print space.

Program:

/**
 * C program to print hollow inverted pyramid 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=n; i>=1; 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 inverted 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