Topic 4 - Repetition Exercise
Topic 4 - Repetition Exercise
1.
What is the output of the following C++ code?
int count = 1;
int y = 100;
while (count < 100)
{
y = y - 1;
count++;
}
cout << " y = " << y << " and count = " << count << endl;
Y=100, count =1 Y=99
Count=2
Y=99, count =2 Y=98
Count =3
Y=98, count =3 Y=97
Count =4
….
Answer:
Y = 1 and count = 100
2.
What is the output of the following C++ code?
int num = 5;
while (num > 5)
num = num + 2;
cout << num << endl;
Num= 5 5
3.
What is the output of the following C++ code?
int num = 1;
while (num < 10)
{
cout << num << " ";
num = num + 2;
}
cout << endl;
Num =1 1
Num =3
Num =3 3
Num =5
Num =5 5
Num =7
Num =7 7
Num =9
Num =9 9
Num =11
Num =11 13579
4.
Suppose that the input is 38 35 71 14 -1. What is the output
of the following code? Assume all
variables are properly declared.
cin >> num;
sum = num;
while (num != -1)
{
cin >> num;
sum = sum + num;
}
cout << "Sum = " << sum << endl;
Num = 38 Sum =38
38!= -1(true)
35
Sum = 38+35
Sum = 73
Num = 35 35!= -1(true)
71
Sum = 73+71
Sum = 144
Num = 71 71!= -1(true)
14
Sum = 144+ 14
Sum = 158
Num = 14 14!= -1(true)
-1
Sum = 158 +(-1)
Sum = 157
Num = -1 Sum =157
5.
35
Num = 35 35!= -1 (true)
Sum = 38 + 35
Sum = 73
71
Num = 71 71!= -1 (true)
Sum = 73+71
Sum = 144
14
Num = 14 14!= -1 (true)
Sum = 144+14
Sum = 158
-1
Num = -1 -1!= -1 (false)
Sum = 158