Program to Print Inverted Full Pyramid Pattern (Star Pattern)
Last Updated :
12 Feb, 2024
Given an integer N, the task is to print a pattern of N rows representing an inverted full pyramid. In this pattern, the first row has (2 * N – 1) stars, the second row has (2 * N – 3) stars, and so on until the Nth row, which has only 1 star. All stars are center-aligned.
Examples:
Input: 3
Output:
*****
***
*
Input: 5
Output:
*********
*******
*****
***
*
Approach:
The problem can be solved using two nested loops inside another loop. The outer loop will run for the rows and the first inner loop will print the spaces and second loop will print stars. If we have an inverted full pyramid pattern with N rows, the 1st row will have 0 space followed by (2 * N – 1) stars, the 2nd row will have 1 space followed by (2 * N – 3) stars, the third row will have 2 spaces followed by (2 * N – 5) stars and so on. So, Nth row will have (N – 1) spaces followed by 1 star.
Step-by-step approach:
- Run an outer loop from i = 1 to the number of rows N.
- Run an inner loop from j = 1 to i – 1.
- Print an empty space (‘ ‘) in each iteration of the inner loop.
- Run an inner loop from j = 1 to 2 * (N – i) + 1.
- Print an asterisk (‘*’) in each iteration of the inner loop.
- Print a newline character (“\n”) to move to the next row.
- After N iterations, we will have the inverted full pyramid pattern.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int main()
{
int N = 5;
for ( int i = 1; i <= N; i++) {
for ( int j = 1; j <= i - 1; j++) {
cout << " " ;
}
for ( int j = 1; j <= 2 * (N - i) + 1; j++) {
cout << "*" ;
}
cout << "\n" ;
}
return 0;
}
|
Java
public class PyramidPattern {
public static void main(String[] args) {
int N = 5 ;
for ( int i = 1 ; i <= N; i++) {
for ( int j = 1 ; j <= i - 1 ; j++) {
System.out.print( " " );
}
for ( int j = 1 ; j <= 2 * (N - i) + 1 ; j++) {
System.out.print( "*" );
}
System.out.println();
}
}
}
|
Python3
N = 5
for i in range ( 1 , N + 1 ):
for j in range ( 1 , i):
print ( " " , end = "")
for j in range ( 1 , 2 * (N - i) + 2 ):
print ( "*" , end = "")
print ()
|
C#
using System;
class Program {
static void Main()
{
int N = 5;
for ( int i = 1; i <= N; i++) {
for ( int j = 1; j <= i - 1; j++) {
Console.Write( " " );
}
for ( int j = 1; j <= 2 * (N - i) + 1; j++) {
Console.Write( "*" );
}
Console.WriteLine();
}
}
}
|
Javascript
let N = 5;
for (let i = 1; i <= N; i++) {
for (let j = 1; j <= i - 1; j++) {
process.stdout.write( " " );
}
for (let j = 1; j <= 2 * (N - i) + 1; j++) {
process.stdout.write( "*" );
}
console.log();
}
|
Output
*********
*******
*****
***
*
Time Complexity: O(N^2), where N is the number of rows in the pattern.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...