C program to print reverse Pyramid star pattern

C program to print reverse Pyramid star pattern

In this article, I will show you, How to write a C program to print reverse pyramid star pattern series of n rows using for loop. How to print reverse Pyramid star pattern in C programming. Here, one thing is important to know that the rows of the pyramid.

Logic to C program to print reverse pyramid star pattern:

  • Enter the row value for the equilateral triangle.
  • Here I have used three loops one is the outer loop to change the line and two inner loops to print star and space.
  • The outer loop iterate row times and print a newline after completing the inner loop.
  • If you will look at the design carefully,  then you will find that the N rows reverse pyramid contain ( (N*2)- ( (2*x) -1) ) star and (x-1)  spaces (where N is the row number and x is the current row number).
  • So to print the space inner loop iterate 1 to x times and to print the star second inner loop iterate 1 to ( (N*2)- ( (2*x) -1) ) times.

See the, C program to print reverse pyramid star pattern:

 

#include <stdio.h>

int main()
{
    int x = 0,y = 0;
    unsigned int rows = 0;

    printf("Enter the number of rows = ");
    scanf("%u",&rows);

    for(x=1; x<=rows; ++x)
    {
        // Print spaces
        for(y=1; y<=x; ++y)
        {
            printf(" ");
        }
        // Print star/
        for(y =1; y <=((rows*2)-((2*x)-1)); ++y)
        {
            printf("*");
        }
        // Print new line
        printf("\n");
    }
    return 0;
}

Output:

print reverse Pyramid star pattern

 

Code Analysis:

It asks the user to enter the row for the pyramid (equilateral triangle).

printf("Enter the number of rows = ");
scanf("%u",&rows);

 

first, inner loop print space 1 to (x-1)  times.

// Print spaces
for(y=1; y<=x; ++y)
{
    printf(" ");
}

 

Second inner loop print star and it will iterate 1 to ( (N*2)- ( (2*x) -1) ) times.

// Print star
for(y =1; y <=((rows*2)-((2*x)-1)); ++y)
{
    printf("*");
}

 

The outer loop print the newline after each iteration of the inner loops.

Recommended Post:



Leave a Reply

Your email address will not be published. Required fields are marked *