What is the output of the following snippet? #include <iostream> #include <string> using namespace std; int f(int a) { return a + a; } int main() { int i = 0; for(int a = 0; a < 2; a++) i = f(i + 1); cout << i; return 0; } 9 6 3 2
Question
What is the output of the following snippet?
#include <iostream> #include <string> using namespace std; int f(int a) { return a + a; } int main() { int i = 0; for(int a = 0; a < 2; a++) i = f(i + 1); cout << i; return 0; }
9
6
3
2
Solution
The output of the given C++ code snippet is 6.
Here's the step-by-step explanation:
-
The function
f(int a)is defined to return the double of the inputa. -
In the
main()function, an integeriis initialized with the value 0. -
A
forloop is set up to run twice (a < 2), withastarting from 0. -
In each iteration of the loop,
iis updated to be the result off(i + 1). -
In the first iteration,
iis 0, soi + 1is 1. The functionf(1)returns1 + 1 = 2, soiis updated to 2. -
In the second iteration,
iis 2, soi + 1is 3. The functionf(3)returns3 + 3 = 6, soiis updated to 6. -
After the loop, the value of
i(which is 6) is printed to the console.
So, the correct answer is 6.
Similar Questions
What is the output for the following code?
What does the following code snippet do?
What is the output of the following code in Python?
What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.
What will be the output of the following PHP code?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.