Program to Print Inverted Right Half Pyramid Pattern (Star Pattern)
Last Updated :
18 Jan, 2024
Given an integer N, print N rows of inverted right half pyramid pattern. In inverted right half pattern of N rows, the first row has N number of stars, second row has (N – 1) number of stars and so on till the Nth row which has only 1 star.
Examples:
Input: n = 5
Output:
*****
****
***
**
*
Input: n = 3
Output:
***
**
*
Approach:
The problem can be solved using two nested loops. The outer loop will run for the rows and the inner loop will print the stars.
Step-by-step algorithm:
- Run an outer loop from i = 1 to the number of rows.
- Run an inner loop from j = 1 to 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 right half pyramid.
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 <= N - i + 1; j++) {
cout << "*";
}
cout << "\n";
}
return 0;
}
|
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
int N = 5 ;
for ( int i = 1 ; i <= N; i++) {
for ( int j = 1 ; j <= 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 , N - i + 2 ):
print (" * ", end = "")
print ()
|
C#
using System;
class MainClass
{
public static void Main( string [] args)
{
int N = 5;
for ( int i = 1; i <= N; i++)
{
for ( int j = 1; j <= N - i + 1; j++)
{
Console.Write( "*" );
}
Console.WriteLine();
}
}
}
|
Javascript
const N = 5;
for (let i = 1; i <= N; i++) {
for (let j = 1; j <= N - i + 1; j++) {
process.stdout.write( "*" );
}
process.stdout.write( "\n" );
}
|
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...