C program to print hollow right triangle star pattern

Write a C program to print hollow right triangle star(*) pattern series using for loop. How to print hollow 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 right triangle star patterns, basic knowledge of printing hollow square star pattern and printing right triangle star pattern is recommended.

Logic:

If you have printed right triangle and hollow square star patterns before then this wouldn't trouble much. If you look to the given pattern carefully you will find that stars are printed only when row=1 or column=1 or column=n (where n is the total number of rows). For this what you need to do is make little change in the right triangle star pattern series i.e. we must check a condition mentioned before printing star(*).

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 number of rows: ");
    scanf("%d", &n);

    for(i=1; i<=n; i++)
    {
        for(j=1; j<=i; j++)
        { 
            if(j==1 || j==i || i==n)
            {
                printf("*");
            }
            else
            {
                printf(" ");
            }
        }

        printf("\n");
    }

    return 0;
} 


Output
X
_
Enter number of rows: 5
*
**
* *
*  *
*****


Screenshot:

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

2 comments:

  1. what is "i" and "j"?

    ReplyDelete
    Replies
    1. 'i' and 'j' are used as counter variables. Where 'i' specifies the number of rows and 'j' specifies the number of columns. You can just take it as normal variables used to print the given series.

      Delete