Nested Loop Examples
Nested Loop Examples
In interactive systems or software, nested loops can generate menus with multiple options and
sub-options.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 2; i++) { // Outer loop for main menu
cout << "Main Menu " << i << endl;
for (int j = 1; j <= 3; j++) { // Inner loop for sub-menu
cout << " Sub-Menu " << j << endl;
}
}
return 0;
}
Write a program in C++ to handle the scenario where you have 5 sections, each containing
10 students. We’ll use nested loops to represent the sections and the students.
int main() {
int totalSections = 5; // Number of sections
int studentsPerSection = 10; // Number of students in each section
return 0;
}
*****
*****
*****
*****
*****
#include <iostream>
using namespace std;
int main() {
int n = 5; // Size of the square
for (int i = 0; i < n; i++) { // Outer loop for rows
for (int j = 0; j < n; j++)
{ // Inner loop for columns
cout << "* ";
}
cout << endl; // Move to the next line
}
return 0;
}
Working Table:
*
**
***
****
*****
#include <iostream>
using namespace std;
int main() {
int n = 5; // Number of rows
for (int i = 1; i <= n; i++) { // Outer loop for rows
for (int j = 1; j <= i; j++) { // Inner loop for columns
cout << "* ";
}
cout << endl; // Move to the next line
}
return 0;
}
Working Table:
*****
****
***
**
*
#include <iostream>
using namespace std;
int main() {
int n = 5; // Number of rows
for (int i = n; i >= 1; i--) { // Outer loop for rows
for (int j = 1; j <= i; j++) { // Inner loop for
columns
cout << "* ";
}
cout << endl; // Move to the next line
}
return 0;
}
Working Table:
1
12
123
1234
12345
#include <iostream>
using namespace std;
int main() {
int n = 5; // Number of rows
for (int i = 1; i <= n; i++) { // Outer loop for rows
for (int j = 1; j <= i; j++) { // Inner loop for
columns
cout << j << " ";
}
cout << endl; // Move to the next line
}
return 0;
}
Working Table: