Write a c++ program to print * pyramid.
Learn how to print a * pyramid in C++ with this simple and easy-to-understand program.#include <iostream>
using namespace std;
int main() {
int n, i, j, k = 0;
cout << "Enter the number of rows for the pyramid: ";
cin >> n;
for (i = 1; i <= n; ++i, k = 0) {
// Print spaces before the stars in each row
for (j = 1; j <= n - i; ++j) {
cout << " ";
}
// Print stars for each row
while (k != 2 * i - 1) {
cout << "*";
++k;
}
cout << endl; // Move to the next line for the next row
}
return 0;
}
-----------
Input: 5
Output:
*
***
*****
*******
*********
Explanation:
- We first include the iostream library which is required for standard input/output operations.
- We then define the main() function which is the starting point of our program.
- We declare variables n, i, j, and k. n is the number of rows for the pyramid, i is the row number, j is the loop counter for spaces, and k is the loop counter for stars.
- We prompt the user to enter the number of rows for the pyramid using cout and cin statements.
- We start a for loop from i = 1 to i = n. Inside this loop, we set k = 0 at the beginning of each iteration because we need to print an odd number of stars in each row.
- We then use another for loop to print the spaces before the stars in each row. The number of spaces in each row decreases by 1 as we move to the next row.
- We then use a while loop to print the stars for each row. The number of stars in each row is 2 * i - 1, where i is the current row number.
- Finally, we use cout to move to the next line for the next row.
- We exit the program by returning 0 from the main() function.
I hope this helps! Let me know if you have any further questions.
No comments:
Post a Comment