중간고사 기출
1. What is the output of the following C++ code?
c++
#include <iostream>
void main()
{
int y = 0;
for (int i = 5; i > 0; i--) {
if(i % 3 == 1)
y++;
else
y += i;
std::cout << "y = " << "\n";
}
} ▶답
y = 5
y = 6
y = 9
y = 11
y = 12
2. The following code generates errors at compile time.
- Find all incorrect statements.
- correct the code and
- show the output of the corrected code
c++
#include <iostream>
void fun(int &r, int v) {
r = r + 100;
v = v - 100;
}
void main()
{
int i = 2;
int j = 3;
int &rl = i;
int &r2;
r2 = j;
fun(i, j);
std::cout << "i : " << i << std::endl;
std::cout << "j : " << j << std::endl;
}- The correct form of the incorrect statements (Write the corrected code)
▶
답
void fun(int &r, int v) {int &r2;
r2 = j;
- The incorrect statements in tha above code:
▶
답
int v → int &vint &r2 = j;
- Output of the working code :
▶
답
i = 102 j = -97 - Is is acceptable(i.e., without generating errors) to modify the definition of the variable ‘i’ to : const int i = 2;
Explain your decision :
▶
답
Because “const” mean it cannot be changed, so trying to modify a const variable in “fun” will result in complie error.
3. Given the following function definition
c++
int g(int x) {
if (x <= 0)
return x + 1;
else
return g(x - 1) + g(x - 1) + g(x - 1);
}- Write an equivalent iterative function definition (loop-based function definition) for the above recursive function:
▶
답
c++int g(int x) { if(x <= 0) return x + 1; int result = 1; for(int i = 1 ; i <= x ; i++) { result = 3 * result; } return result; } - What is the returned value for g(3)?
▶
답
27 - What will be the returned value for g(100) if the condition in the second line of the function is altered from x ≤ 0 to x < 0.
▶
답
0