The left half pyramid is a common pattern-printing problem in C++ that uses spaces and asterisks to form a right-aligned triangle.
- The number of rows determines the height of the pyramid.
- Nested loops are used to print spaces and asterisks in each row.
Illustration
Input:
rows = 5Output:
*
* *
* * *
* * * *
* * * * *
Using for Loop
The outer for loop controls the number of rows. For each row, the first inner loop prints the required spaces, while the second inner loop prints the asterisks.
For a row i, the number of leading spaces is rows - i, and the number of asterisks is i.
#include <iostream>
using namespace std;
int main()
{
int rows = 5;
// first for loop is used to identify number of rows
for (int i = rows; i > 0; i--) {
// second for loop is used to identify number of
// columns and here the values will be changed
// according to the first for loop
for (int j = 0; j <= rows; j++) {
// if j is greater than i then it will print
// the output otherwise print the space
if (j >= i) {
cout << "*";
}
else {
cout << " ";
}
}
cout << "\n";
}
return 0;
}
Output
*
**
***
****
*****
Explanation: For each row, the program first prints spaces and then prints asterisks. As the row number increases, the number of spaces decreases by one and the number of asterisks increases by one.
Using while Loop
The same pattern can also be generated using while loops. The outer loop controls the rows, while one inner loop prints spaces and another prints asterisks.
#include <iostream>
using namespace std;
int main()
{
int i = 0, j = 0, sp = 0;
int rows = 5;
// while loop check the condition until the given
// condition is false if it is true then enteres in to
// the loop
while (i < rows) {
// second while loop is used for printing spaces
while (sp < (rows - i - 1)) {
cout << " ";
sp++;
}
// assigning sp value as 0 because we need to run sp
// from starting
sp = 0;
// this loop will print the pattern
while (j <= i) {
cout << "* ";
j++;
}
j = 0;
i++;
cout << "\n";
}
return 0;
}
Output
*
* *
* * *
* * * *
* * * * *
Explanation: The outer while loop processes one row at a time. For each row, the first inner loop prints the required number of spaces, and the second inner loop prints the corresponding number of asterisks.