C++ Program to Print Number Pattern
for loops; for example, for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { std::cout << j << ' '; } std::cout << '\n'; } prints numbers from 1 up to the current line number.Examples
How to Think About It
Algorithm
Code
#include <iostream> int main() { int n; std::cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { std::cout << j << ' '; } std::cout << '\n'; } return 0; }
Dry Run
Let's trace input 3 through the code
Input read
n = 3
First outer loop iteration (i=1)
Inner loop runs j=1; prints '1 '
Print newline after first row
Output: '1 \n'
Second outer loop iteration (i=2)
Inner loop runs j=1,2; prints '1 2 '
Print newline after second row
Output: '1 \n1 2 \n'
Third outer loop iteration (i=3)
Inner loop runs j=1,2,3; prints '1 2 3 '
Print newline after third row
Output: '1 \n1 2 \n1 2 3 \n'
| i (row) | j (column) | Printed Number |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 1 | 1 |
| 3 | 2 | 2 |
| 3 | 3 | 3 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, each iteration representing one row of the pattern.
Step 2: Inner loop prints numbers
The inner for loop runs from 1 to the current row number, printing numbers in increasing order.
Step 3: Newline after each row
After printing numbers for a row, std::cout << '\n' moves the cursor to the next line for the next row.
Alternative Approaches
#include <iostream> int main() { int n; std::cin >> n; for (int i = n; i >= 1; i--) { for (int j = 1; j <= i; j++) { std::cout << j << ' '; } std::cout << '\n'; } return 0; }
#include <iostream> int main() { int n; std::cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { std::cout << i << ' '; } std::cout << '\n'; } return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The nested loops run approximately n*(n+1)/2 times, which is O(n^2), because for each row i, the inner loop runs i times.
Space Complexity
The program uses constant extra space, O(1), as it only stores loop counters and prints output directly.
Which Approach is Fastest?
All approaches use nested loops with similar time complexity; differences are mainly in output style, not performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Counting up pattern | O(n^2) | O(1) | Simple increasing number patterns |
| Reverse number pattern | O(n^2) | O(1) | Decreasing rows pattern |
| Same number per row | O(n^2) | O(1) | Patterns with repeated numbers per row |