Pyramid pattren program in C++
#include <iostream>
int main() {
int rows;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
std::cout << "* ";
}
std::cout << std::endl;
}
return 0;
}
Explanation:
The above code is a C++ program to print a pyramid pattern using asterisks. It prompts the user to enter the number of rows for the pyramid and then prints the pattern accordingly.
- The
#include <iostream>
statement includes the necessary header file for input/output operations. - The
int main()
function is the entry point of the program. - The
int rows;
declaration creates a variable to store the number of rows entered by the user. - The
std::cout << "Enter the number of rows: ";
statement displays a prompt asking the user to enter the number of rows. - The
std::cin >> rows;
statement reads the user input and stores it in therows
variable. - The outer
for
loop is used to iterate over each row of the pyramid. It starts from1
and continues untili
reaches the number of rows entered by the user. - Inside the outer loop, there is an inner
for
loop. This loop is used to print the asterisks for each row. It starts from1
and continues untilj
reaches the current row numberi
. - Inside the inner loop, the statement
std::cout << "* ";
is used to print an asterisk followed by a space. - After printing the asterisks for a row, the statement
std::cout << std::endl;
is used to move to the next line. - After the inner loop completes for a row, the outer loop moves to the next row and repeats the process.
- Finally, the
return 0;
statement indicates the successful termination of the program.