#include <iostream>
using namespace std;
int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}
return 0;
}Output
Enter number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Number Pattern in C++
This program teaches you how to print a number pattern using nested loops in C++. Instead of printing stars, this pattern prints numbers in a sequential order. Each row displays numbers from 1 up to the row number, creating a triangular number pattern. This is an excellent way to understand how to use loop variables in output and transition from character patterns to number patterns.
What is a Number Pattern?
A number pattern looks like this (for 5 rows):
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Notice:
- Each row starts from 1
- Each row ends at the row number
- Row 1 has numbers 1
- Row 2 has numbers 1, 2
- Row 3 has numbers 1, 2, 3
- And so on...
Understanding the Pattern Logic
The key insight is: ## In row i, we print numbers from 1 to i.
This means:
- Row 1: Print 1 to 1 →
1 - Row 2: Print 1 to 2 →
1 2 - Row 3: Print 1 to 3 →
1 2 3 - Row 4: Print 1 to 4 →
1 2 3 4 - Row 5: Print 1 to 5 →
1 2 3 4 5
Key Difference: Printing j vs Printing i
This is an important concept:
-
cout << j;→ Prints the inner loop variable (1, 2, 3, 4, 5...) -
cout << i;→ Would print the outer loop variable (1, 2, 2, 2, 3, 3, 3, 3...)
Using j gives us the sequential number pattern we want.
Summary
- The outer loop (
i) controls which row we're printing (1 to rows). - The inner loop (
j) runs from 1 toi, printing each number. - We print
j(noti) to get sequential numbers 1, 2, 3, 4... - After each row,
endlmoves to the next line. - This creates a number pattern where each row contains numbers from 1 to the row number.
This program is essential for understanding how to use loop variables in output and creating numeric patterns. It's a foundation for more complex number patterns and mathematical visualizations.