Ömer Çiftci Ömer Çiftci - 1 month ago 10
C Question

I cant write this factorial codes

I have some problem with that. I am trying to learn C programming. Please help me

#include<stdio.h>


int main()
{
int a, factorial;

printf("Please enter a value :" );

scanf("%d", &a);


for (int i = 1; i<=a; i++)
{
a = (a - 1)*a;
}
printf("%d", factorial);
return 0;
}

Answer

Well in your code line a = (a - 1)*a; you actually changed your input for getting the factorial. It also will blow your loop. See your for loop will continue as long as your i is less than a, lets say you choose a=3 after first iteration the a itself will become 6, so the for loop will continue until it reach the integer limit and you will get overflow error.

What you should do?

First of all you should use a second variable to store the factorial result, you introduced it as factorial, the way that @danielku97 said is a good way to write a factorial since if you present 0 as input it will also give the correct result of 1. so a good code is:

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

But lets say you insist of subtraction, the way you just tried to use, then you need to change the code like:

scanf("%d", &a);
if (a==1 || a==0){
    printf("1");
    return 0;
}

factorial = a;
for (int i = 1; i<a; i++) 
{
factorial *= (a - i)*factorial;
}

You can see that the code just got unnecessarily longer. An if included to correct the results for 1 and 0. Also you need to make sure that i never become like i =a since in that case a-i will be equal to zero and will make the factorial result equal to zero.

I hope the explanations can help you on learning C and Algorithm faster.

Comments