C++ Program To Print Inverted Pyramid
Last Updated :
23 Feb, 2023
Here we will build a C++ Program To Print Inverted Pyramid using 3 different approaches:
- Half Inverted Using “*”
- Half Inverted Using Numbers
- Full Inverted Pyramid using ” * “
1. Program to print inverted half Triangle using ” * “
Input:
n=4
Output:
* * * *
* * *
* *
*
As we can observe from the given example the number of printed rows is equal to the given input n and the number of printed columns is decreasing from n to 1. Therefore we run the outer for loop from n to 1 and the inner for loop from 1 to row number
Example:
C++
using namespace std;
#include <bits/stdc++.h>
#include <iostream>
int main()
{
int n = 4;
for ( int i = n; i >= 1; --i) {
for ( int j = 1; j <= i; ++j) {
cout << "* " ;
}
cout << endl;
}
return 0;
}
|
Output
* * * *
* * *
* *
*
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.
2. Program to print an inverted half pyramid using numbers
Input
n=4
Output:
1 2 3 4
1 2 3
1 2
1
By looking at the given example we can try to run the outer for loop from n to 1 and for each row traversal, we should print the elements from 1 to the row number. This means instead of printing * we need to print that specific column number.
Example:
C++
using namespace std;
#include <bits/stdc++.h>
#include <iostream>
int main()
{
int n=4;
for ( int i = n; i >= 1; --i) {
for ( int j = 1; j <= i; ++j) {
cout << j << " " ;
}
cout << endl;
}
return 0;
}
|
Output
1 2 3 4
1 2 3
1 2
1
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.
3. Program to print inverted full pyramid using ” * “
Input:
n = 4
Output:
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Example:
C++
using namespace std;
#include <bits/stdc++.h>
#include <iostream>
int main()
{
int n=5;
for ( int i = n; i >= 1; --i) {
for ( int k = 0; k < n - i; ++k) {
cout << " " ;
}
for ( int j = i; j <= 2 * i - 1; ++j) {
cout << "* " ;
}
for ( int j = 0; j < i - 1; ++j) {
cout << "* " ;
}
cout << endl;
}
return 0;
}
|
Output
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Time complexity: O(n2) for given input n
Space complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...