To print a pyramid pattern in C++, you can use nested loops where the outer loop controls the rows and the inner loops control the spaces and stars printed in each row.
In this example,
printPyramid
that takes an integer n
as input to represent the number of rows in the pyramid.cout
to move to the next line.#include <iostream>
void printPyramid(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++)
std::cout << " ";
for (int k = 1; k <= 2 * i - 1; k++)
std::cout << "*";
std::cout << std::endl;
}
}
int main() {
printPyramid(5);
return 0;
}
* *** ***** ******* *********
In this tutorial, we learned How to print Pyramid Pattern in C++ language with well detailed examples.