Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading