Search code examples
c++for-loopparameter-passingfactorialmodular-design

3 Function plus Main Function C Program calculating and displaying a Factorial


The first function needs to get the number and pass it back to main, this value then needs to be passed into a second function that calculates the factorial and passes that value back to main with the result being printed in the third and final function.

The program calculates the factorial of a number that is input. I need to keep the for loop. I'm not sure what's going wrong, I get garbage values back, so I think I'm losing a value somewhere or not storing a value.

Also any general help is appreciated.

#include <stdio.h>

void GetData(int &x)
{
    printf("Please enter a number:\n");
    scanf("%d%*c", &x);

    return;
}

int Factorial(int x)
{
    int factorial = 1;
    int i;

    for(i = 1; i <= x; i++)
    {
        factorial = factorial * i;
    }

    return(x);
}

void PrintResults(int factorial)
{
    printf("The factorial = %d\n", factorial);

    return;
}

int main()
{
    int x, factorial;

    GetData(x);

    Factorial(x);


    PrintResults(factorial);

    return(0);
}

Solution

  • First of all, you should change your call to GetData to :

    GetData(&x);
    

    as you want to pass a pointer. Then, its declaration should change to :

    void GetData(int *x)
    {
        printf("Please enter a number:\n");
        scanf("%d%*c", x);
    }
    

    Then, you should return variable factorial instead of x. Change line :

    return(x);
    

    to :

    return(factorial);
    

    and consequently call Factorial function as follows :

    factorial = Factorial(x);
    

    as right now, variable factorial is uninitialized, and by passing it to Factorial you will be getting garbage, as you said.