Search code examples
cloopsfactorial

Factorial program in c


Trying to make a code that gets the factorial of the inputted number.

int factorial(int number, int i)
{
    int endval;
    for(i = number - 1; i>0; i--){
        endval = number * i;
    }
    if (endval == 0){
        printf("1");
    }
    return endval;
}

int main()
{
    int endvalue, numA, numB;
    char userchoice[1];
    printf("Enter a choice to make (f for factorial): \n");
    scanf("%s", userchoice);
    if(strcmp(userchoice, "f")== 0){
        printf("Enter a value to get it's factorial: ");
        scanf("%d", &numA);
        endvalue = factorial(numA, numB);
        printf("%d", endvalue);
        return 0;}


    getch();
    return 0;
}

For some reason the whole for loop doesn't do anything in the function when I set the answer (number*i)= endval. It just prints out the same number I inputted and gives me an absurd answer for 0!.

int factorial(int number, int i)
{
    int endval;
    for(i = number - 1; i>0; i--){
            endval = number * i;
    }
    if (endval == 0){
        printf("1");
    }
    return endval;
}

However the code works perfectly fine when I remove endval variable entirely (with the exception that it gets 0! = 10)

int factorial(int number, int i)
{
    for(i = number - 1; i>0; i--){
        number = number * i;
    }
    if (number == 0) {printf("1");}
    return number;
}

Is there anything I missed in the code that's causing these errors?


Solution

  • #include <stdio.h>
    #include <string.h>
    
    int factorial(int number)
    {
        int endval=1;
        for(int i = number ; i>0; i--){
            endval *= i;
        }
        return endval;
    }
    
    int main()
    {
    
        int endvalue=0;
        int numA=0;
    
        char userchoice[1];
        printf("Enter a choice to make (f for factorial): ");
        int ret=scanf("%s", userchoice);
        if (!ret){
            printf("Error in scanf: %d", ret);
        }
        if(strcmp(userchoice, "f")== 0){
            printf("Enter a value to get it's factorial: ");
            scanf("%d", &numA);
            endvalue = factorial(numA);
            printf("%d", endvalue);
            return 0;
        }
    
        getchar();
        return 0;
    }
    

    Code with some changes will work

    • factorial() function can get only one argument.
    • As a good habit all variables must be initialized.
    • Add include statement to source and be explicit not rely on compiler. As we use strcmp() we must include string.h
    • use standard getchar() instead of getch()
    • Also can check return value of library function scanf() to ensure reading is correct or not.
    • You can use warnings from compiler to get most of above notes. In gcc: gcc -Wall code.c
    • Use a debugger to run program line by line and monitor variables value in each steps or use as many printf() to see what happens in function call.