#include<stdio.h>
long int fact(int n);
long int Ifact(int n);
main( )
{
int num;
printf("Enter a number : ");
scanf("%d", &num);
if(num<0)
printf("No factorial for negative number\n");
else
printf("Factorial of %d is %ld\n", num, fact(num) );
if(num<0)
printf("No factorial for negative number\n");
else
printf("Factorial of %d is %ld\n", num, Ifact(num) );
}/*End of main()*/
/*Recursive*/
long int fact(int n)
{
if(n == 0)
return(1);
return(n * fact(n-1));
}/*End of fact()*/
/*Iterative*/
long int Ifact(int n)
{
long fact=1;
while(n>0)
{
fact = fact*n;
n--;
}
return fact;
}/*End of ifact()*/
Enter a number : 5
Factorial of 5 is 120
Factorial of 5 is 120
Press any key to continue . . .
/*Recursive*/
long int fact(int n)
{
if(n == 0)
return(1);
return(n * fact(n-1));
}/*End of fact()*/
/*Iterative*/
long int Ifact(int n)
{
long fact=1;
while(n>0)
{
fact = fact*n;
n--;
}
return fact;
}/*End of ifact()*/
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.