๐
Date: Feb 3, 2026
๐ฅ Topic: Nested Loops & Basic Patterns
๐จ Why Draw with Code?
Pattern printing isn't just about making pretty shapes. It is the best way to master Nested Loops.
The Golden Rule:
1. Outer Loop (i) controls the Rows.
2. Inner Loop (j) controls the Columns.
1️⃣ Square Pattern (The Warmup)
Simple N x N grid of stars.
****
****
****
****
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
cout << "*";
}
cout << endl;
}
2️⃣ Right Angled Triangle
Here, the number of stars equals the row number.
*
**
***
****
for(int i=1; i<=n; i++) {
// Inner loop runs 'i' times
for(int j=1; j<=i; j++) {
cout << "*";
}
cout << endl;
}
3️⃣ Number Triangle
Instead of stars, we print the column number.
1
12
123
1234
for(int i=1; i<=n; i++) {
for(int j=1; j<=i; j++) {
cout << j;
}
cout << endl;
}
4️⃣ Floyd's Triangle (Flooding Numbers)
We keep a counter variable that keeps increasing.
1
2 3
4 5 6
7 8 9 10
int count = 1;
for(int i=1; i<=n; i++) {
for(int j=1; j<=i; j++) {
cout << count << " ";
count++;
}
cout << endl;
}
๐ญ Thoughts
The key is finding the relationship between i and j. Once you crack the formula, the code writes itself.
No comments:
Post a Comment