Number Pattern in C++
Four number triangles in C++: 1..j, row index, countdown, Floyd (num++). Same loops, different cout.
1#include <iostream>2using namespace std;34int main() {5 int rows;67 cout << "Enter number of rows: ";8 cin >> rows;910 // Pattern 1: Increasing numbers11 cout << "\nPattern 1:" << endl;12 for (int i = 1; i <= rows; i++) {13 for (int j = 1; j <= i; j++) {14 cout << j << " ";15 }16 cout << endl;17 }1819 // Pattern 2: Same number in row20 cout << "\nPattern 2:" << endl;21 for (int i = 1; i <= rows; i++) {22 for (int j = 1; j <= i; j++) {23 cout << i << " ";24 }25 cout << endl;26 }2728 // Pattern 3: Decreasing numbers29 cout << "\nPattern 3:" << endl;30 for (int i = 1; i <= rows; i++) {31 for (int j = i; j >= 1; j--) {32 cout << j << " ";33 }34 cout << endl;35 }3637 // Pattern 4: Floyd's Triangle38 cout << "\nPattern 4 (Floyd's Triangle):" << endl;39 int num = 1;40 for (int i = 1; i <= rows; i++) {41 for (int j = 1; j <= i; j++) {42 cout << num++ << " ";43 }44 cout << endl;45 }4647 return 0;48}
Output
Enter number of rows: 5 Pattern 1: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Pattern 2: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Pattern 3: 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 Pattern 4 (Floyd's Triangle): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
What's going on
Four number triangles, same nested-loop skeleton, different thing in cout. Sample rows = 5.
Pattern 1 — cout << j: 1 / 1 2 / 1 2 3 / … That's the beginner Number Pattern page.
Pattern 2 — cout << i: 1 / 2 2 / 3 3 3 / 4 4 4 4 / 5 5 5 5 5. The row index, repeated.
Pattern 3 — j from i down to 1: 1 / 2 1 / 3 2 1 / … Last cell of the row is always 1.
Pattern 4 — Floyd. int num = 1; outside both loops, then cout << num++. Numbers keep going: 1 / 2 3 / 4 5 6 / 7 8 9 10 / 11 12 13 14 15.
Put num = 1 inside the outer loop and Floyd dies — every row starts at 1 again.
The loops are identical: i is the row, j <= i is how many cells. Only the printed value changes. That's the whole trick.