C program to print hollow inverted right triangle star pattern

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

Logic:

You will find this pattern easier if you are done with hollow right triangle and inverted right triangle star patterns. If you haven't here is a simple logic behind this pattern.

First is total number of characters(including stars and spaces) per row decreases as row number increases(i.e. first row contains 5 characters and afterwards second contains 4 and so on...) means each row contains n - row_number + 1 characters(where n is the total number of rows).

Second is stars(*) only gets printed for row=1 or column=1 or column=n(Where n is the total number of rows to be printed). And spaces gets printed when stars don't.

Program:

/**
 * C program to print hollow 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);

    //Outer loop for iterating over rows
    for(i=1; i<=n; i++)
    {
        for(j=i; j<=n; j++)
        {
            /*
             * Stars gets printed only for row=1, column=1 or column=n
             */
            if(i==1 || j==i || j==n)
            {
                printf("*");
            }
            else
            {
                //Print spaces if stars don't get printed
                printf(" ");
            }
        }

        printf("\n");
    }

    return 0;
} 


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


Screenshot:

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