Triangle patterns are useful for practicing nested loops and understanding how rows, columns, spaces, and symbols are controlled in C++.
- Each pattern uses nested loops to control the number of spaces and symbols printed in every row.
- The number of spaces or stars changes according to the row number to create the required shape.
Right Triangle
For n rows, the ith row contains i stars. The outer loop controls the rows, while the inner loop prints the required number of stars.
Illustration
Input: 4
Output:
*
* *
* * *
* * * *
#include <iostream>
using namespace std;
int main(){
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << "* ";
cout << endl;
}
return 0;
}
Output
* * * * * * * * * * * * * * *
Inverted Right Triangle
For n rows, the ith row contains n - i + 1 stars. The number of stars decreases by one after every row.
Illustration
Input: 5
Output:
* * * * *
* * * *
* * *
* *
*
#include <iostream>
using namespace std;
int main(){
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i + 1; j++)
cout << "* ";
cout << endl;
}
return 0;
}
Output
* * * * * * * * * * * * * * *
Alternative Implementation
The same pattern can also be generated by starting the outer loop from n and decreasing it to 1.
#include <iostream>
using namespace std;
int main()
{
int n = 5;
for (int i = n; i >= 1; i--)
{
for (int j = 1; j <= i