C++ Program To Print Left Half Pyramid Pattern
Here, we will build a C++ program to print the left half of pyramid pattern using 2 approaches i.e.
- Using for loop
- Using while loop
1. Using for loop
Input:
rows = 5
Output:
*
**
***
****
*****
First, for loop is used to identify the number of rows and the second for loop is used to identify the number of columns. Here the values will be changed according to the first for loop. If j is greater than i then it will print the output otherwise print the space.
C++
#include <iostream>
using namespace std;
int main()
{
int rows = 5;
for ( int i = rows; i > 0; i--) {
for ( int j = 0; j <= rows; j++) {
if (j >= i) {
cout << "*" ;
}
else {
cout << " " ;
}
}
cout << "\n" ;
}
return 0;
}
|
Output
*
**
***
****
*****
Time complexity: O(n2)
Here n is number of rows.
Auxiliary Space: O(1)
As constant extra space is used.
2. Using while loop
Input:
rows = 5
Output:
*
**
***
****
*****
The while loops check the condition until the condition is false. If the condition is true then it enters into the loop and executes the statements.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0, j = 0, sp = 0;
int rows = 5;
while (i < rows) {
while (sp < (rows - i - 1)) {
cout << " " ;
sp++;
}
sp = 0;
while (j <= i) {
cout << "* " ;
j++;
}
j = 0;
i++;
cout << "\n" ;
}
return 0;
}
|
Output
*
* *
* * *
* * * *
* * * * *
Time complexity: O(n2) where n is number of rows
Space complexity: O(1)
Last Updated :
23 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...