简体   繁体   中英

Factorial of a number in C

So I was Writing a program to print the factorial of a number in C. My code -

#include <stdio.h>
int main(void)
{
    int a,i ;
    printf("Enter the number = ");
    scanf("%d", &a);

    for(i=1; i<a; i++)
    {
        a = a*i;
    }
    printf("The factorial of the given number is = %d\n",a);
}

Now this program is printing some garbage value. I asked some friends and they said to add another variable for factorial and use the loop with that factorial variable, but none of them knew why is this code wrong.

My question is as to why is this code wrong? What is this For loop doing here and why is it not printing the factorial of the number, but some garbage value?

Expected output-

Enter the number = 5
The factorial of the given number is = 120

The Output that I am getting is-

Enter the number = 5
The factorial of the given number is = -1899959296

Because when you increment your variable a , the for loop condition change. You have that i must be lesser than a , but incrementing a will cause the condition to always be true. You have to save the value in another variable, like this:

#include <stdio.h>
int main(void)
{
    int a, i;

    printf("Enter the number = ");
    scanf("%d", &a);
    int result = a;
    
    for(i=1; i<a; i++){
        result = result*i;
    }
    
    printf("The factorial of the given number is = %d \n", result);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM