I have this code in C that has to calculate a factorial of a number entered by keyboard, once the factorial has been calculated, the option to start the program again to calculate another factorial is shown.
#include <stdio.h>
int main() {
int num,c,rep,factorial;
printf("Introduzca el numero del que desea calcular el factorial: \n");
scanf("%d",&num);
c=num;
do{
factorial=factorial*c;
c--;
}while(c=1);
printf("El factorial de %d es %d \n",num,factorial);
printf("Si desea volver a iniciar el programa pulse 1 si no, pulse cualquier otro numero\n");
scanf("%d",&rep);
if(rep==1){
main();
}
else{
printf("Fin del programa\n");
}
return 0;
}
My problem is that the program does not calculate the factorial, an infinite loop is generated in do while
it and I know what the problem is. Thank you very much.
your code has 2 simple errors and that's why it doesn't work. When you loop
do while
in the condition you make the loop execute whilec=1
that means the loop will be executing infinitely if the number entered is not 1.The other error that your code has is that you do not initialize the value of the factorial variable to 1, therefore it is assigned a random value and your code does not calculate the factorial correctly.
To fix this error just change the loop condition and say
c!=1
what will cause the factorial loop to run as long as c is different from 1.The modified code would look like this:
With these modifications your code should work.