Learn C++ nested loops by tracing outer and inner iterations, printing star and number patterns, and using break and continue in beginner-friendly examples.
By the end of this lecture, students will be able to:
break to terminate a loop.continue to skip an iteration.A nested loop is a loop placed inside another loop.
Think of a classroom with 3 rows of students, with 4 students in each row. The outer loop represents the rows, while the inner loop represents the students in each row.
|  |
The outer loop runs once for each row. For every outer-loop iteration, the inner loop completes all its iterations.
for Loops – Printing a Rectangle PatternA nested loop is a loop placed inside another loop.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= 5; j++)
{
cout << "* ";
}
cout << endl;
}
return 0;
}
Output:
* * * * *
* * * * *
* * * * *
* * * * *
Code Explanation: Read the complete solution with algorithm, pseudocode, dry run, and line-by-line explanation →
cout << endl; starts a new row.Try changing the program to produce these patterns.
Pattern A — Rectangle of numbers
1 2 3 4
1 2 3 4
1 2 3 4
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
cout << "* ";
}
cout << endl;
}
return 0;
}
Output:
*
* *
* * *
* * * *
* * * * *
The key statement is:
for (int j = 1; j <= i; j++)
Unlike the previous example, the inner loop depends on the outer loop’s counter i.
i = 1, print 1 star.i = 2, print 2 stars.i = 3, print 3 stars.* with #.1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 4; i++)
{
for (int j = 1; j <= i; j++)
{
cout << i << " ";
}
cout << endl;
}
return 0;
}
Output:
1
2 2
3 3 3
4 4 4 4
Notice the difference between i and j:
i determines the row number and the value printed.j determines how many times that value is printed.Produce this pattern:
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
Hint: Keep the inner loop’s condition independent of i, so every row contains four numbers.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 3; i++)
{
cout << "Table of " << i << endl;
for (int j = 1; j <= 5; j++)
{
cout << i << " x " << j
<< " = " << i * j << endl;
}
cout << endl;
}
return 0;
}
Sample output:
Table of 1
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
Table of 2
2 x 1 = 2
2 x 2 = 4
...
The outer loop selects the table. The inner loop calculates five multiplication results for each table.
Solve Coding Exercises 29–31 in the Nested Loop section. Write, run, and test each C++ program to verify the output.