user2147550
user2147550

Reputation:

cant get program to calculate correct factorial of a number

I wrote a program to give the factorial of a number entered by the user. It is for an assignment and it must be written so the first function reads in a value then passes it to the main then the main passes this to a second function which calculates the factorial of the number then prints it to the user. The problem is it keeps showing '1' as every number's factorial. What am I doing wrong?

#include <stdio.h>

int getValue()
{

    int n;

    printf("Enter number: ");
    scanf("%d%*c", &n);

    return(n);
}

int factorial(int n)
{

    int i, f;

    f=1;
    for(i=1; i<=n; i++)
    f=f*i;

    printf("The factorial is: %d", f);

    return(f);
}

int main()
{

    int f;

    getValue();
    factorial(f);

    return(0);
}

Upvotes: 0

Views: 227

Answers (1)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158599

You are not setting f this should fix your problem:

int main()
{
    int f = getValue();
    factorial(f);

    return(0);
}

I am assuming that you have a typo in the code with the scanf since it would not compile otherwise but it should be:

scanf("%d%*c", &n);
            ^  

Upvotes: 2

Related Questions