C++ Program To Print Right Half Pyramid Pattern
Last Updated :
23 Feb, 2023
Here we will build a C++ Program To Print Right Half Pyramid Pattern with the following 2 approaches:
- Using for loop
- Using while loop
Input:
rows = 5
Output:
*
* *
* * *
* * * *
* * * * *
1. Using for loop
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.
C++
#include <iostream>
using namespace std;
int main()
{
int rows = 5;
for ( int i = 1; i <= rows; i++) {
for ( int j = 1; j <= i; j++) {
cout << "* " ;
}
cout << "\n" ;
}
return 0;
}
|
Output
*
* *
* * *
* * * *
* * * * *
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.
2. Using while loop
The while loops check the condition until the condition is false. If condition is true then enters in to loop and execute the statements.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 0, j = 0;
int rows = 5;
while (i < rows) {
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...