C++ Nested Loop
C++ Nested Loop
2019/2020
C++ Lab
Nested Loop
Objectives:
Student should be able to:
For Loop:
Example #1:
Write a c++ program to print the numbers from 0 to 10 using for loop
#include <iostream>
using namespace std;
void main(){
Exercise:
Write a c++ program to print the numbers from 10 to 0 using for loop
Notes:
1|Page
Example #2:
Write a c++ program to print the even numbers from 10 to 0 using for loop
#include <iostream>
using namespace std;
void main(){
Example #3:
#include <iostream>
using namespace std;
void main(){
int sum = 0;
for (int i = 5; i <= 50; i += 3) {
sum += i;
}
cout << "The sum is: " << sum << endl;
Example #4:
Write a c++ program asks the user to enter 5 characters using for loop, if the
user enters 'n' exit the loop.
#include <iostream>
using namespace std;
void main(){
char ch;
for (int i = 0; i <= 5; i++){
cout << "Enter charactar " << i <<" :";
cin >> ch;
if (ch == 'n')
break;
}
Example #5:
2|Page
Write a c++ program to print numbers from 10 to 0 using for loop except the
number 5
#include <iostream>
using namespace std;
void main(){
for (int n = 10; n>0; n--) {
if (n == 5)
continue;
cout << n << ", ";
}
}
Nested Loop:
Example #1:
Write a c++ program to print the multiplication table of the numbers from 0 to
5
#include <iostream>
using namespace std;
void main(){
for (int multi = 0; multi <= 5; multi++){
for (int multi2 = 0; multi2 <= 10; multi2++){
cout << multi << "*" << multi2 << "= "<<multi *multi2 <<
endl;
}
cout << endl;
}
Example#2:
#include <iostream>
using namespace std;
void main(){
3|Page
{
for (int y = 1; y <= x; y++)
cout << "*";
cout << endl;
}
Example #3:
#include <iostream>
using namespace std;
void main(){
}
}
4|Page
Example #4:
#include <iostream>
using namespace std;
void main(){
In Lab work:
Using the previous example, write a c++ program to print the following shape
5|Page
Full example:
#include <iostream>
using namespace std;
void main(){
int sum = 0;
for (int i = 5; i <= 50; i += 3) {
sum += i;
}
cout << "The sum is: " << sum << endl;
char ch;
for (int i = 0; i <= 5; i++){
cout << "Enter charactar " << i << " :";
cin >> ch;
if (ch == 'n')
break;
}
6|Page
cout << "--------------------------------------------------------------------" <<
endl;
7|Page
Good Luck
8|Page