Triangle Patterns in C++
1. Basic Concepts Involved
To create triangle patterns, you need:
- Nested loops: An outer loop to handle the rows and an inner loop to handle the
columns/characters.
- Conditionals (sometimes): To control special patterns like hollow triangles.
- cout and endl for printing.
2. Left-Aligned Triangle Pattern
Theory
This triangle has its left side aligned. For n rows:
- Row 1 → 1 star
- Row 2 → 2 stars
- ...
- Row n → n stars
Code
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter number of rows: ";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Example Output (n = 5)
*
**
***
****
*****
3. Right-Aligned Triangle Pattern
Theory
This is aligned to the right side. For this:
- First print spaces, then stars.
- Spaces decrease as rows increase.
Code
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter number of rows: ";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
cout << " ";
}
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Example Output (n = 5)
*
**
***
****
*****
4. Pyramid (Centered Triangle)
Theory
- This pattern is symmetrical.
- Each row has:
- Decreasing spaces on the left.
- Increasing stars (odd numbers: 1, 3, 5…).
Code
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter number of rows: ";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
cout << " ";
}
for (int j = 1; j <= 2 * i - 1; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}
Example Output (n = 5)
*
***
*****
*******
*********
5. Hollow Right-Angled Triangle
Theory
- Only borders of the triangle are shown using `*`.
- Use `if` statements inside inner loop.
Code
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter number of rows: ";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if (j == 1 || j == i || i == n) {
cout << "* ";
} else {
cout << " ";
}
}
cout << endl;
}
return 0;
}
Example Output (n = 5)
*
**
* *
* *
*****
6. Summary of Logic Patterns
| Pattern Type | Key Logic |
|---------------------|----------------------------------------|
| Left-aligned | j <= i |
| Right-aligned | Print spaces n - i then j <= i |
| Centered Pyramid | Spaces then j <= 2*i - 1 stars |
| Hollow Triangle | if (j == 1 || j == i || i == n) |