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


    Question

    Consider the following C code snippet:    

    #include     int factorial(int n) {         if (n == 0) {             return 1;         }         // Potential error here         return n * factorial(n);      }     int main() {         printf("%d\n", factorial(3));         return 0;     }     What will be the output or behavior of the program when factorial(3) is called?
    A 6 Correct Answer Incorrect Answer
    C 3 Correct Answer Incorrect Answer
    D A segmentation fault or stack overflow Correct Answer Incorrect Answer
    E Compilation error Correct Answer Incorrect Answer

    Solution

    The error lies in the recursive call: return n * factorial(n);. Instead of calling factorial(n - 1) to move towards the base case, the function calls itself with the same argument n. This creates an infinite recursion loop. When factorial(3) is called, it calls factorial(3) again, which calls factorial(3) indefinitely. Each call consumes stack memory, eventually leading to a stack overflow and typically a segmentation fault. The correct recursive call should be return n * factorial(n - 1);.

    Practice Next
    ask-question