Monday, February 16, 2015

C Programming: Non-recursive and Recursive Programs for Getting the Factorial of a Number

No comments :
Here are programs that compute for the factorial of a number both non-recursively and recursively.

Here is the non-recursive way:

Non-recursive Factorial Output

 #include<stdio.h>  
   
 int factorial(int num)  
 {  
      int i;  
        
      for(i=num-1;i>1;i--)  
      {  
           num=num*i;  
      }  
      return num;  
 }  
   
 main()  
 {  
      int num,ans;  
        
      clrscr();  
      printf("Non-recursive\n\n");  
      printf("Enter number: ");  
      scanf("%d",&num);  
      ans=factorial(num);  
      printf("The factorial of %d is %d.",num,ans);  
      getch();  
 }  

Here is the recursive way:
Recursive Factorial Output

 #include<stdio.h>  
   
 int factorial(int num)  
 {  
      if(num==1) //We don't have to multiply the number by 1 since it will just be the same number  
      {  
           return 1;  
      }  
      else  
      {  
           num=num*factorial(num-1);  
           return num;  
      }  
 }  
   
 main()  
 {  
      int num,ans;  
        
      clrscr();  
      printf("Recursive\n\n");  
      printf("Enter number: ");  
      scanf("%d",&num);  
      ans=factorial(num);  
      printf("The factorial of %d is %d.",num,ans);  
      getch();  
 }   

If you have questions on these, place a comment below.

No comments :

Post a Comment