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
For the first time in the world a rare and fatal brain amoeba has been found in which country?
In which state of India a new portal “Amar Sarkar” is being launched by the Chief Minister
Which author won the Sahitya Akademi Yuva Puraskar for her memoir "Homeless: Growing up Lesbian and Dyslexic in India"?
Which ancient city in Uttar Pradesh is associated with the birth of Jain Tirthankara Parshvanatha?
Deoband Movement in Uttar Pradesh was started in which of the following year?
Which Indian author is known for the contemporary novel "The White Tiger," which won the Man Booker Prize in 2008?
For how many days Kumbh Mela is celebrated?
When is World Refugee day observed ?
Which ministry organized the Poshan Utsav event in February 2024?
A transaction banking platform NEO for Business has been launched for the Indian Micro, Small and Medium Enterprises (MSMEs) that will offer features li...