Question
Consider the following C code snippet:
#include int recursiveSum(int n) { static int sum = 0; // Static variable if (n > 0) { sum += n; recursiveSum(n - 1); } return sum; } int main() { printf("First call: %d\n", recursiveSum(3)); printf("Second call: %d\n", recursiveSum(2)); return 0; } What will be the output of the main function?Solution
The key here is the static int sum = 0; declaration. A static variable is initialized only once when the program starts and retains its value across multiple function calls. First call: recursiveSum(3) sum is initialized to 0 (only once). recursiveSum(3): n=3. sum becomes 0 + 3 = 3. Calls recursiveSum(2). recursiveSum(2): n=2. sum becomes 3 + 2 = 5. Calls recursiveSum(1). recursiveSum(1): n=1. sum becomes 5 + 1 = 6. Calls recursiveSum(0). recursiveSum(0): n=0. The if (n > 0) condition is false. Returns the current value of sum, which is 6. All preceding calls return this value. So, printf("First call: %d\n", recursiveSum(3)); prints "First call: 6". Second call: recursiveSum(2) sum does not reset to 0. It retains its value of 6 from the previous execution. recursiveSum(2): n=2. sum becomes 6 + 2 = 8. Calls recursiveSum(1). recursiveSum(1): n=1. sum becomes 8 + 1 = 9. Calls recursiveSum(0). recursiveSum(0): n=0. The if (n > 0) condition is false. Returns the current value of sum, which is 9. All preceding calls return this value. So, printf("Second call: %d\n", recursiveSum(2)); prints "Second call: 9". Therefore, the output is: First call: 6 Second call: 9
Which of the following were the significance of Cripps MIssion proposal?
1. The British government acknowledged India’s right to be a dom...
What is card tokenization?
Which one of the following is not a tributary of the river Godavari?
Closure compensation eligibility requires:
3rd Framework Working Group meeting under the Finance Track of India's G20 Presidency will be held at the Bolghatty Island, Bolghatty Island is situated...
As of July 2022, PM-VIKAS is aligned to the 15th Finance Commission cycle period up to _________ and is a Central Sector (CS) scheme under the Ministry ...
Which type of union emphasizes political action, mutual insurance programs, and cooperative enterprises?
The ratio of length to breadth of a rectangle is 8:5. When the length and breadth of the rectangle is increased by 20% and decreased by 30% respectively...
Which of the following falls under Article 51A of the Indian Constitution?
Which state celebrated “Utkal Day ”