Pattern Programs in C++ (Nested Loops)
In this lesson: Nested loops and pattern programs in C++ — stars, numbers, pyramids — with code and output. In Hindi & English.
What are nested loops?
A nested loop is simply a loop inside another loop. For every single pass of the outer loop, the inner loop runs all the way through. This two-level counting is exactly what you need to print patterns.
Thinking in rows and columns
The trick to every pattern is this: the outer loop is the row, and the inner loop is the column (what to print across that row). Decide how many rows you want, then decide what each row should contain.
A square of stars
Each of 3 rows prints 3 stars:
for (int i = 1; i <= 3; i++) { // rows
for (int j = 1; j <= 3; j++) { // columns
cout << "* ";
}
cout << "\n"; // new line after each row
}
| i (row) | Andar j chalta hai | Print hota hai |
|---|---|---|
| 1 | j=1,2,3 | * * * |
| 2 | j=1,2,3 | * * * |
| 3 | j=1,2,3 | * * * |
Nested loop me bahar wala loop (i) rows banata hai, andar wala (j) us row me columns. Har baar bahar wala ek row aage badhta hai, andar wala poora chal ke us row ke saare star print karta hai.
* * *
* * *
* * *
A right triangle
Make the inner loop depend on the row number, so row i prints i stars:
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) { // note: j <= i
cout << "* ";
}
cout << "\n";
}*
* *
* * *
* * * *
A number triangle
Print the column number instead of a star:
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << "\n";
}1
1 2
1 2 3
1 2 3 4
A pyramid
A pyramid adds a spaces loop before the stars — spaces shrink as stars grow:
int rows = 4;
for (int i = 1; i <= rows; i++) {
for (int s = 1; s <= rows - i; s++) cout << " "; // spaces
for (int j = 1; j <= 2 * i - 1; j++) cout << "*"; // stars
cout << "\n";
}*
***
*****
*******
Common mistakes
- Forgetting the
cout << "\n";after each row, so everything prints on one line. - Using
j <= 3(fixed) when you meantj <= i(grows with the row). - Getting the spaces count wrong in a pyramid — it is
rows - i. - Reusing the same variable name for both loops, breaking the counting.
Print an inverted right triangle (4 stars on top, 1 at the bottom). Then try a number pyramid. Change one loop bound at a time and watch how the shape changes.
Summary
- A nested loop runs the inner loop fully for each outer pass.
- For patterns: outer loop = rows, inner loop = what fills each row.
- Make the inner bound depend on
ito get triangles. - Pyramids add a spaces loop before the stars.
- Always print a newline at the end of each row.
