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
Who is the author of the book "A Part Apart: The Life and Thought of B.R. Ambedkar"?
IREDA's Loan Book grew by _____ percent, reaching Rs . 59,698 . 11 crores as of March 31, 2024 .
Exercise DUSTLIK 2023 was organized between India and which country?
Which of the following startup of India became 100th unicorn startup?
Exercise MALABAR 2024 is a significant maritime engagement under the Eastern Naval Command. Which countries participate in this exercise?
Which organisation recently entered into a co-lending partnership with C2treds and UGRO Capital to facilitate loans to the MSME sector?
Who has been appointed as the new head of the Defense Intelligence Agency?
Consider the following about the RBI circular on card-on-file (CoF) tokenisation?
I. CoF refers to card information stored by payment gateway and...
Which of the following countries has the House of Lords in its Parliament ?
Which country is the top-ranked Asian side in the latest FIFA rankings?