C++ Nested Loops (With Examples) - Algbly
C++ Nested Loops (With Examples) - Algbly
Once all the condition within the inner loop gets satisfied and becomes true it moves for the search of the outer
loop. It is often called a loop within a loop .
while (condition) {
while (condition) {
// body of inner while-loop
}
// body of outer while-loop
}
do {
do{
// body of inner do-while-loop
}while (condition);
// body of outer do-while-loop
}while (condition);
#include <iostream>
using namespace std;
int main() {
int weeks = 1, days_in_week = 7;
Output
Week: 1
Day:1
Day:2
Day:3
Day:4
Day:5
Day:6
Day:7
We can create nested loops with while and do...while in a similar way.
Example 2: Displaying a Pattern
#include <iostream>
using namespace std;
int main() {
int i, j, n;
cout << "Enter Number : ";
cin >> n;
return 0;
}
Output
Enter Number : 4
*
* *
* * *
* * * *
The inner loop iterates from 1 to columns . Inside the inner loop, we print the character '*' .
// C++ program to display a triangular pattern of numbers using nested while loop
#include <iostream>
using namespace std;
int main() {
int rows, i = 1;
cout << "Enter the number of rows: ";
cin >> rows;
Output
Enter the number of rows: 4
1
22
333
4444
The inner loop iterates from 1 to i . Inside the inner loop, we print the numbers.
// C++ program to display a triangular pattern of numbers using nested do-while loop
#include <iostream>
using namespace std;
int main() {
return 0;
}
Output
Example 4: C++ break Inside Nested Loops
// C++ program to display a triangular pattern of numbers using nested do-while loop
#include <iostream>
using namespace std;
int main() {
int weeks = 3, days_in_week = 2;
Output
Week: 1
Day:1
Day:2
Week: 2
Week: 3
Day:1
Day:2
This program does not run the inner loop when the value of i is 2 i.e. it does not print the days of the 2nd week. The
outer loop that prints the weeks is unaffected.
Similarly, when we use a continue statement inside the inner loop, it skips the current iteration of the inner loop only.
The outer loop is unaffected. For example,
// C++ program to display a triangular pattern of numbers using nested do-while loop
#include <iostream>
using namespace std;
int main() {
int weeks = 3, days_in_week = 7;
Week: 1
Day:1
Day:3
Day:5
Day:7
Week: 2
Day:1
Day:3
Day:5
Day:7
Week: 3
Day:1
Day:3
Day:5
Day:7
Whenever the days_in_week is even, the continue statement skips that iteration of the inner loop.
We hope that this tutorial helped you develop better understanding of the concept of Nested Loops in C++.
Keep Learning : )
- Related Topics
What's next?
We are already working on a new project, so stay tuned.
Tutorials
Your Future, Make it Better
The more you learn, the less you pay. Delivering great education, free & accessibly to everyone.
Java Programming
About
About
Contact
© 2020 AlgBly. Some rights reserved Terms & conditions Privacy Policy