0% found this document useful (0 votes)
5 views

Lab 6

Uploaded by

2022478618
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lab 6

Uploaded by

2022478618
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

C++ Lab Module

Lan

Lab 6

Control Structure: Repetition

1. For Loop

Syntax
The syntax of a for loop in C++:

for (initial; condition; increment)


{
statement(s);
}

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:

Sum even integer numbers between 0 to 10 using for statement.

int main ()
{
int sum = 0;
for (int i = 2; i<10; i= i + 2)
{
sum = sum + i;
}
cout<< " The sum = "<< sum<<endl;
}

The tracing table below will check the output:

i i < 10 sum = sum + i i=i+2


2 yes 2 4
4 yes 6 6
6 yes 12 8
8 yes 20 10
10 no

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:

1. Write for statements to print out the following sequences of values:

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:

i. EVEN numbers from 0 to 20


ii. ODD numbers in descending orders from 15 to 1.

3. Write a C++ program for the following problem.

Use for loop to accept 10 integer numbers from user. The program will count
and display the total number of ODD and EVEN numbers.

4. Use for loop statements to solve the following problem.

You might also like