C program to print hollow mirrored inverted right triangle star pattern

Write a C program to print hollow mirrored inverted right triangle star(*) pattern series of n rows using for loop. How to print hollow mirrored inverted right triangle star pattern 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 you must go through how to print hollow inverted right triangle star pattern.

Logic:

If you look to the pattern carefully you will find that it is way similar to hollow inverted right triangle if we add trailing spaces. So what we need is we need to make a little change in the hollow inverted right triangle star pattern program, we need to add an extra inner loop that will print spaces before the star gets printed. And if you look to the spaces you will notice they are in a special pattern (i.e. spaces per row is spaces = row_number - 1).

Program:

/**
 * C program to print hollow mirrored inverted right 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 before star gets printed
        for(j=1; j<i; j++)
        {
            printf(" ");
        }

        //Prints hollow inverted right triangle
        for(j=i; j<=n; j++)
        {
            if(j==i || j==n || i==1)
            {
                printf("*");
            }
            else
            {
                printf(" ");
            }
        }

        printf("\n");
    }

    return 0;
} 


Output
X
_
Enter value of n: 5
*****
 *  *
  * *
   **
    *


Screenshot:

C program to print hollow mirrored inverted right 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