You are on page 1of 3

Computer Skills -2 (C++) (0206102)

Worksheet #4 – Part One


CONTROL STRUCTURES - (REPETITION)

** C++ has three repetition or looping structures that allow you to repeat a set of
statements until certain conditions are met.
1. while Looping (Repetition) Structure:

Example:

#include <iostream>
using namespace std;
int main ( )
{
int num = 1;
//while loop execution
while( num < 10 )
{
cout << "value of num: " << num << endl;
num++;
}
return 0; }

2. for Looping (Repetition) Structure:


Example:

#include <iostream>
using namespace std;
int main ( )
{
// for loop execution
for( int i = 10; i < 10; i = 1 + 1 )
cout << "value of i: " << i << " ";
return 0;
}

1
Abdullah Shbtat
Exercises:

1. What is the output of the following C++ code?


int a = 1, count = 1;
while (count < 100)
{
a += 2;
count++;
}
cout << " a = " << a << endl;

2. What is the output of the following program?


#include<iostream.h>
int main( )
{
int num = 1;
while (num < 12)
{
cout << num << " ";
num = num + 3;
}
cout << endl;
return 0;
}

3. What is the output of the following program? Suppose that the input is: 58 23 46
#include <iostream>
using namespace std;
int main( )
{
int a, b, c;
cin>>a>>b>>c;
while(((++a + b - 7) % 6) != 0)
{
cout << a << " ";
}
cout << endl;
return 0;
}

2
Abdullah Shbtat
4. What is the output of the following C++ program segment?
int count = 0;
while (count++ < 10)
cout << "This loop can repeat statements." << endl;

5. Write a program that uses while loop to find the sum of the following series:
1 + (2 / 1) + (3 / 2) + (4 / 3) + (5 / 4)+ ... + (10 / 9)

6. Write a program that uses while loop to find the sum of the following numbers, except the
last number:
17, 32, 62, 48, 58, -1

7. What is the output of the following C++ program segment?

{
int i,j;
for (j = 0; j < 4; j++)
{
cout << j * 25 << " - ";
if (j != 7)
cout << (j + 1) * 25 - 1 << endl;
else
cout << (j + 1) * 25 << endl;
}

8. Rewrite the following as a for loop.

int i = 0, value = 0;
while (i <= 20)
{
if (i % 2 == 0 && i <= 10)
value = value + i * i;
else if (i % 2 == 0 && i > 10)
value = value + i;
else
value = value - i;
i = i + 1;
}

9. Rewrite Exercise 5 using for loop.

3
Abdullah Shbtat

You might also like