Quantcast
Channel: Engineers Press » Ankit
Viewing all articles
Browse latest Browse all 15

C language: Program for finding factorials with recursion and with loops

$
0
0

This is another program which is very basic and the code is for the same program, in one block only loops are used to find the factorial in C language and in the other program recursion is used with loops to get the same result. So now why is there a  recursion one if we can do the same thing without it.

Its because recursion helps us in making the code more maintainable and readable also recursion provides us with a more natural way of writing the same program and if required the function can also be used in other programs and will increase re-usability too.

So here’s the code for finding factorial with loops :


#include <stdio.h>

int main()
{
 int c, n, fact = 1;

 printf("Enter a number to calculate it's factorial\n");
 scanf("%d", &n);

 for (c = 1; c <= n; c++)
 fact = fact * c;

 printf("Factorial of %d = %d\n", n, fact);

 return 0;
}

and here’s the code for the same program using recursion technique:


#include<stdio.h>

long factorial(int);

int main()
{
 int n;
 long f;

 printf("Enter an integer to find factorial\n");
 scanf("%d", &n);

 if (n < 0)
 printf("Negative integers are not allowed.\n");
 else
 {
 f = factorial(n);
 printf("%d! = %ld\n", n, f);
 }

 return 0;
}

long factorial(int n)
{
 if (n == 0)
 return 1;
 else
 return(n * factorial(n-1));
}



Viewing all articles
Browse latest Browse all 15

Trending Articles