Чтобы создать полупирамиду в C++, можно использовать различные методы. Вот несколько разных подходов:
Метод 1: использование вложенных циклов и звездочек
#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;
}
Метод 2: использование одного цикла и звездочек
#include <iostream>
int main() {
int rows;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
for (int i = 1; i <= rows; ++i) {
std::cout << std::string(i, '*') << std::endl;
}
return 0;
}
Метод 3: использование одного цикла и чисел
#include <iostream>
int main() {
int rows;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
for (int i = 1; i <= rows; ++i) {
std::cout << std::string(i, std::to_string(i)[0]) << std::endl;
}
return 0;
}
Метод 4. Использование рекурсии
#include <iostream>
void printHalfPyramid(int rows) {
if (rows == 0)
return;
printHalfPyramid(rows - 1);
for (int i = 0; i < rows; ++i)
std::cout << "* ";
std::cout << std::endl;
}
int main() {
int rows;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
printHalfPyramid(rows);
return 0;
}