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
निम्नलिखित प्रश्न में , दिए गए चार विकल्पों में से , उस विक�...
निम्ननलिखित प्रश्न में कौनसा विकल्प सही नहीं है ?
निम्नलिखित वाक्यों के रिक्त स्थान पर उसके नीचे दिए गए ...
निम्नलिखित शब्दों में से अतिकर का सही पर्याय है ?
"खेल खत्म, पैसा हजम" का अर्थ है:
निम्नलिखित में से ' विचित्र ' का पर्यायवाची क्या होगा ?
निम्नलिखित प्रत्येक प्रश्न में दिए गए शब्द के समानार�...
भारत सरकार ने हिन्दी को राजभाषा के रूप में कब स्वीकार �...
‘स्नेह’ शब्द का पर्यायवाची नहीं है:
मुहावरा “आँख दिखाना” का सही अर्थ है —