position: fixed; top: auto !important; margin-left: 112px;
Copied to clipboard..

C program to print star pattern as a right triangle

In this tutorial, we will practice the concepts of Basic C programming, If else, For loop and Nested loop with the help of a very basic program. This C program is used to print star pattern as a right triangle. This article's reading time is almost 3 min 17 sec. So let's get started.

   
    Table of Contents
    
  • What is the Problem Statement?
  • How we will approach to solve the star pattern?
  • C Program to print start pattern
  • Output
  • Problem Statment

    The task is to print the following star pattern,

    *
    **
    ***
    ****
    *****
    

    How we will approach to solve the star pattern?

    I solve these star pattern problems using the concept of "Star increment/decrement and Space Increment/Decrement". You can solve any star pattern problem with the help of this concept. Though it is not defined in any book, I find it useful while solving the problems.

    So basically, the concept is if you notice in the first line of output, there is 1 star and 4 spaces. In the second line, there are 2 stars and 3 spaces. In the third line, there are 3 stars and 2 spaces. In the fourth line, there are 4 stars and 1 spaces. In the fifth line, there are 5 stars and 0 spaces.

    So, whenever the value of star increases, the value of spaces decreases. Let's try to implement this in a C program.

    
    
     #include <stdio.h>
    
    int main(void) {
    	
    for(int i = 0; i < 5; i++)
    {
        for(int k = 0; k <= i; k++)
        {
        printf("*");
        }
        for(int j = 5; j > i;j--)
        {
            printf(" ");
        }
        printf("\n");
        
    }
    	return 0;
    }
    

    Output:

    *
    **
    ***
    ****
    *****
    

    In the given program, the first loop is to make ensure that there should be 5 steps while printing the pattern.

    For two inner loops, Let's try to read the given code. At first, the value of k is 0 and k <= 0, so * gets printed. Then j = 5 to j < 0 will print 4 spaces. Then new line character brings the pointer to next line. Again, the outer loop with index i = 1 checks i & 5 or not. As condition is true, k = 0 and k < 1 prints two stars. Then, j = 5; j > 1 prints 3 spaces. Then, new line character brings the pointer to the next line. Similarly, you can try to read the program for index i = 3 & 4.

    If you have any doubts, you can ask in the below comment section.



    Previous Next Article








    codzify.com


    Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

    Social Profile


    Linkedin
    Twitter
    Facebook

    Copyright 2018. All rights reserved.