Gandhara
Gandhara

Reputation: 1

Incorrect factorial calculation

I've just made a program that calculates the factorial of integers in the int-interval. I've also inserted a while loop so it keeps running forever.

But i've got a problem because of this loop: for example if I type the number 5 the first time, i get the output 120 which is fine since 5!=120. But the second time i type 5, i get a completely other number (it's the same case with ALL numbers at 2. attempt). I think it's because my program keeps saving the value of 'factorial' or the loop counter 'c'.

So i basically need to reset both variables after each time a factorial is calculated, but i don't know to to do this reset!

Here is my code:

int main(void) {    

    uart_init(); // open the communication to the microcontroller
    io_redirect(); // redirect input and output to the uart

    int number; 
    int c;
    int factorial=1;

    while(1){
        printf("Please enter an integer to calculate its factorial:\n");
        scanf("%d", &number);       //Our input number is stored in the variable 'number'

        for (c=1; c<=number;++c)    //The variable 'c' is incremented by 1, until it equals 'number' (input)
            factorial=factorial*c;  //Every time 'c' is incremented by 1, it is multiplied with 'factorial' which initially is 1. 

        printf("Factorial of %d is %d\n\n\n", number, factorial);   //The factorial is printed.
    }
    return(0);
}

Upvotes: 0

Views: 209

Answers (5)

haccks
haccks

Reputation: 106082

Put

int factorial=1; 

inside the while loop.

while(1){
    // Reset factorial by 1
    int factorial=1; 
    printf("Please enter an integer to calculate its factorial:\n");
    scanf("%d", &number);      
    for (c=1; c<=number;++c)   
        factorial = factorial*c;  

    printf("Factorial of %d is %d\n\n\n", number, factorial);   
}

Upvotes: 0

Igor Pejic
Igor Pejic

Reputation: 3698

Add factorial = 1 in the while loop, so the body of the while loop looks like this:

while(1){
printf("Please enter an integer to calculate its factorial:\n");
scanf("%d", &number);       //Our input number is stored in the variable 'number'

for (c=1; c<=number;++c)    //The variable 'c' is incremented by 1, until it equals 'number' (input)
    factorial=factorial*c;  //Every time 'c' is incremented by 1, it is multiplied with 'factorial' which initially is 1. 

printf("Factorial of %d is %d\n\n\n", number, factorial);   //The factorial is printed.
factorial = 1;
}

Upvotes: 0

Christopher Schneider
Christopher Schneider

Reputation: 3915

You're re-using factorial without re-initializing it. You need to set it to 1 at the start of the while loop.

Upvotes: 1

Bmo
Bmo

Reputation: 1212

You need to reset factorial inside the loop.

Upvotes: 1

ThreeFx
ThreeFx

Reputation: 7360

Add

factorial = 1; 

At the end of the while-loop.

Upvotes: 1

Related Questions