Home > Software design >  Factorial of a number in C
Factorial of a number in C

Time:05-10

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

CodePudding user response:

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);
}
  • Related