5.13. Multiple Choice ExercisesΒΆ
Q1
What is the output of the code below?
int main() {
int x = 0;
int i = 1;
while (i < 10) {
x = i;
i++;
}
cout << x;
}
Q2
What is the final value of i when the code is finished running?
int main() {
int x = 0;
int i = 1;
while (i < 10) {
x = i;
i++;
}
cout << x;
}
Q3
How many times does the following while loop run?
int main() {
int i = 6;
while (i > 2) {
i = i + 4;
if (i > 8) {
i = i - 5;
}
}
}
Q4
What is the output of the code below?
int main() {
int n = 10;
// cout << "Da ";
cout << "na ";
while (n != 3) {
cout << "na ";
n--;
}
cout << "Batman!";
}
Q5
What is the output of the code below?
int main() {
int n = 10;
cout << "Da ";
cout << "na ";
while (n != 3) {
cout << "na ";
}
cout << "Batman!";
}
Q6
What is the output of the code below?
int main() {
int x = 1;
while (x < 6) {
cout << x << '\t' << pow (x, 5) / pow (x, 3) << '\n';
x++;
}
}
Q7
Why are we allowed to use the variable x in both main and in the function definition of super_secret_function?
int super_secret_function (int n) {
int x = 0;
return (2 + (n * n) - 5 * n / 7) * x;
}
int main() {
int x = 1;
cout << "After using the super secret function, we get " << super_secret_function (x);
}
Q8
What is the output of the code below?
int loop_five (int n) {
while (n % 5 != 0) {
n = n + 3;
}
return n;
}
int main() {
cout << loop_five (2);
cout << loop_five (3);
cout << loop_five (4);
}
Q9
The super evil villian re_pete wants to annoy the city by hacking into the city's helper robots and making them repeat everything they say 5 times. However, there's an error in his code and now the robots won't stop repeating! Can you find the error?
void repeat_bot (string input) {
int n = 0;
while (n < 5) {
cout << input << ' ';
n--;
}
}
int main() {
repeat_bot ("Hello, how may I help you?");
}
Q10
After making some changes to his code, re_pete tries again. This time, however, the robots don't repeat anything! Can you find the new error?
void repeat_bot (string input) {
int n = 0;
while (n > 5) {
cout << input << ' ';
n++;
}
}
int main() {
repeat_bot ("Hello, how may I help you?");
}