Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cant fix a logical error in a recursion function

If post fix decrement(--x) is equal to (x-1) so why when I change factorial(n-1) to factorial(--n)it gives me a logical error of output = 0

#include<stdio.h>

int factorial (int n) {
    int fact=1;
    if (n>=1) {
        fact=n*factorial(n-1);
    }
    return fact;
}

void main (void) {
    int x , y ;
    printf("Please Enter a Number : ");
    scanf("%d",&x);
    y=factorial(x);
    printf("Factorial = %d ",y);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

factorial(n-1) to factorial(–n)it gives me a logical error of output
= 0

It is undefined by C language standard.

But probable explanation of the observable behaviour is: if n == 1 then

fact=n*factorial(--n);

n will become zero before calling factorial. So if n == 1 then it will become

fact=0*factorial(0);

Which is always 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading