📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider the following C code snippet for calculating

    base raised to the power of exp:     #include     double power(double base, int exp) {         if (exp == 0) {             return 1;         }         // Missing handling for negative exponent         return base * power(base, exp - 1);     }     int main() {         printf("%.2f\n", power(2.0, -2));         return 0;     }     What will be the output or behavior of the program when power(2.0, -2) is called?
    A 0.25 Correct Answer Incorrect Answer
    B 4.00 Correct Answer Incorrect Answer
    C 0.00 Correct Answer Incorrect Answer
    D A segmentation fault or stack overflow Correct Answer Incorrect Answer
    E Compilation error Correct Answer Incorrect Answer

    Solution

    The power function correctly handles exp == 0 and positive exp. However, it lacks a specific base case or handling for negative exponents. When power(2.0, -2) is called, exp is -2, which is not 0. The function then calls base power(base, exp - 1), which becomes 2.0  power(2.0, -3). This process continues indefinitely, with exp becoming more and more negative (-4, -5, etc.). The exp will never reach the base case of 0, leading to infinite recursion, a stack overflow, and typically a segmentation fault. To fix this, a condition for exp < 0 should be added, typically return 1.0 / power(base, -exp);.

    Practice Next
    ask-question