Lab 6
Lab 6
Lan
Lab 6
1. For Loop
Syntax
The syntax of a for loop in C++:
Example 1:
int main ()
{
for (int a = 10; a < 20; a = a + 1)
{
cout << "value of a: " << a << endl;
}
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
1
C++ Lab Module
Lan
Example 2:
int main ()
{
int sum = 0;
for (int i = 2; i<10; i= i + 2)
{
sum = sum + i;
}
cout<< " The sum = "<< sum<<endl;
}
Output:
The sum = 20
Example 3:
Display odd numbers between 0 – 20 and calculate the frequency of these odd numbers.
int main ()
{
int odd = 0;
for(int i = 0; i<20; i++)
{
if (i%2 != 0)
{
cout<< i << " ";
odd++;
}
}
cout<< "\nThere are "<<odd<< " odd numbers "<< endl;
}
2
C++ Lab Module
Lan
Output:
1 3 5 7 9 11 13 15 17 19
There are 10 odd numbers
Example 4:
Write a C++ program to display following output:
54321
int main()
{
for(int i = 5; i > 0; i--)
{
cout<< i << " ";
}
}
Tracing table:
i i>0 cout<< i i --
5 yes 5 4
4 yes 4 3
3 yes 3 2
2 yes 2 1
1 yes 1 0
0 no
3
C++ Lab Module
Lan
Exercise:
i 12345678
ii. 3 8 13 18 23
iii. 20 14 8 2 -4 -10
2. Produce the output that will display integer numbers based on following:
Use for loop to accept 10 integer numbers from user. The program will count
and display the total number of ODD and EVEN numbers.