C Program For Printing Inverted Pyramid

  • The vacant spaces will be printed using a for loop.
  • To print the triangle from the left side, a for loop will be needed.
  • A for loop is going to be utilized to print the remaining triangle, resulting in the perfect design.

Algorithm:

  • Set variables i, j, and space to represent rows, columns, and blank spaces, accordingly.
  • The number of rows in this example is 7, but the user may select any number.
  • Create a for loop that will serve as the main loop in printing the pattern and will control the other loops contained within it.
  • Begin a for loop to print the blank spaces within the main loop.
  • To begin printing the star design, first print the half pyramid as illustrated below. To do so, we'll start a for loop with the condition 2 * i - 1, so the number of stars is odd.
  • Following that, we'll apply the other for loop to print the remainder of the pattern.

The C code below demonstrates how to create an inverted pyramid pattern:

C Programming Language:

Example

#include <stdio.h>

int main()
{
int rows = 7, i, j, space;

for (i = rows; i >= 1; --i)
{

	for (space = 0;
			space < rows - i; ++space)
		printf(" ");

	for (j = i; j <= 2 * i - 1; ++j)
		printf("* ");
	for (j = 0; j < i - 1; ++j)
		printf("* ");
	printf("\n");
}

return 0;
}

Output

Output

* * * * * * * * * * * * * 
 * * * * * * * * * * * 
  * * * * * * * * * 
   * * * * * * * 
    * * * * * 
     * * * 
      *
  • Time Complexity will be O(n 2 ).
  • Auxiliary Space will be O(1).

Method 2: Implementing two for loops:

  • A for loop will handle the printing of empty spaces.
  • Another for loop will manage the printing of asterisks.

Algorithm:

  • Set variables I j, and rows to their initial values.
  • The row count here is seven, but the user can choose any number.
  • Create a for loop that will serve as the main loop in displaying the pattern and will drive the other loops contained within it.
  • Create a for loop that will run from 1 to I and will print the blanks inside the main loop.
  • To print the stars, run a for loop from 1 through rows 2 - I 2 - 1).
  • With the help of the new line character, go to the following line.

The C code provided below generates an inverted pyramid pattern:

C Programming Language:

Example

#include <stdio.h>

// Driver code
int main()
{
	int i, j, rows = 7;

	for (i = 1; i <= rows; i++)
	{
		for (j = 1; j < i; j++)
		{
			printf(" ");
		}
		for (j = 1;
			j <= (rows * 2 - (2 * i - 1));
			j++)
		{
			printf("*");
		}
		printf("\n");
	}

	return 0;
}

Output

Output

*************
 ***********
  *********
   *******
    *****
     ***
      *
  • Time Complexity will be O(n 2 ).
  • Auxiliary Space will be O(1).

Input Required

This code uses input(). Please provide values below: