user2147550
user2147550

Reputation:

c program to calculate factorial not working

Hi I have to write this program which calculates a factorial of a given number. The first function must read in a number, then pass this to the main function which passes that value to a second function, which calculates the factorial of that number, then passes that factorial to the main.a third function should then be called from the main which displays the factorial Here is what I wrote and I can't get it to work:

    #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;

        return(f);
    }

    void printFactorial(int f)
    {

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

        return;
    }

    int main()
    {

        int f = getValue();
        factorial(f);
        printFactorial();

        return(0);
    }

Upvotes: 0

Views: 1170

Answers (5)

Rahul shantagiri
Rahul shantagiri

Reputation: 1

int main()
{

    int f = getValue();
    factorial(f);
    printFactorial(f);
    getch();
    return(0);
}

Upvotes: -1

anshul garg
anshul garg

Reputation: 503

You are not passing value to printFactorial(). Pass the value to the printing function: You can store factorial(f) result to some variable and then paas or you can pass factorial(f) to printing function

Upvotes: 1

Burkhard
Burkhard

Reputation: 14738

I think you are missing a parameter for printFactorial().

Try this:

printFactorial(factorial(f));

Upvotes: 1

NPE
NPE

Reputation: 500773

You are ignoring the return value of factorial() and are not passing the argument to printFactorial(). These are the most obvious problems.

Another, most subtle, issue is that factorial() will only work for small values of n. The factorial function grows so rapidly that you'll quickly encounter integer overflow.

Upvotes: 0

P.P
P.P

Reputation: 121417

You are not passing the calculated factorial value to printFactorial(). Pass the value to the printing function:

int main()
{

    int f = getValue();
    int fact = factorial(f);
    printFactorial(fact);
    return(0);
}

Upvotes: 2

Related Questions