C++ Program to Print Right Triangle Pattern
for loops in C++ where the outer loop controls rows and the inner loop prints stars; for example, for(int i=1; i<=n; i++){ for(int j=1; j<=i; j++) cout << "*"; cout << endl; } prints a right triangle pattern.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { cout << "*"; } cout << endl; } return 0; }
Dry Run
Let's trace input 5 through the code to see how the right triangle pattern is printed.
Input
User inputs n = 5
Outer loop iteration 1
i = 1; inner loop runs j = 1; prints '*' once; prints newline
Outer loop iteration 2
i = 2; inner loop runs j = 1 to 2; prints '**'; prints newline
Outer loop iteration 3
i = 3; inner loop runs j = 1 to 3; prints '***'; prints newline
Outer loop iteration 4
i = 4; inner loop runs j = 1 to 4; prints '****'; prints newline
Outer loop iteration 5
i = 5; inner loop runs j = 1 to 5; prints '*****'; prints newline
| Row (i) | Stars Printed |
|---|---|
| 1 | * |
| 2 | ** |
| 3 | *** |
| 4 | **** |
| 5 | ***** |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, representing each row of the triangle.
Step 2: Inner loop prints stars
The inner for loop runs from 1 to the current row number, printing that many stars.
Step 3: Newline after each row
After printing stars for a row, cout << endl; moves the cursor to the next line for the next row.
Alternative Approaches
#include <iostream> using namespace std; int main() { int n, i = 1; cin >> n; while (i <= n) { int j = 1; while (j <= i) { cout << "*"; j++; } cout << endl; i++; } return 0; }
#include <iostream> using namespace std; void printStars(int count) { if (count == 0) return; cout << "*"; printStars(count - 1); } void printTriangle(int row, int n) { if (row > n) return; printStars(row); cout << endl; printTriangle(row + 1, n); } int main() { int n; cin >> n; printTriangle(1, n); return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The outer loop runs n times and the inner loop runs up to n times in the last iteration, resulting in roughly n*(n+1)/2 operations, which is O(n^2).
Space Complexity
The program uses constant extra space for loop variables and output, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; iterative for loops are simplest and most efficient in practice.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simplicity and readability |
| Nested while loops | O(n^2) | O(1) | Alternative loop style |
| Recursion | O(n^2) | O(n) | Learning recursion, elegant code |