C++ program to print half pyramid pattern of numbers and stars
ADVERTISEMENTS
In this article, you will learn how to print the half pyramid patterns of the numbers and stars in the c++ programming language.
Examples
Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Enter the number of rows: 5
*
* *
* * *
* * * *
* * * * *
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++
main()
function - C++
for
loop statement - C++
if
condition statement - C++
increment
operator - C++
cin
object - C++
cout
object
1. C++ program to print half pyramid pattern of numbers
// C++ program to print half pyramid pattern of numbers
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
if (rows > 0) {
cout << endl;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}
}
return 0;
}
Output
Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
2. C++ program to print half pyramid pattern of stars
// C++ program to print half pyramid pattern of stars
#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter the number of rows: ";
cin >> rows;
if (rows > 0) {
cout << endl;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << "*" << " ";
}
cout << endl;
}
}
return 0;
}
Output
Enter the number of rows: 5
*
* *
* * *
* * * *
* * * * *
3. C++ program to print half pyramid pattern of Alphabets
// C++ program to print half pyramid pattern of Alphabets
#include <iostream>
using namespace std;
int main() {
int rows;
char alphabet = 'A';
cout << "Enter the number of rows: ";
cin >> rows;
if (rows > 0) {
cout << endl;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << alphabet << " ";
}
alphabet++;
cout << endl;
}
}
return 0;
}
Output
Enter the number of rows: 5
A
B B
C C C
D D D D
E E E E E
Explanation
In the given program, we have taken input 5
from the user and passed this input for loop iteration.
Then It follows the perspective logic to print the pattern.