Breaking

Wednesday, April 17, 2019

Program no: 7(C) C program to find Factorial of a Number using Reccursion

C program to find the factorial using recurrsion
Write a recursive function in C to find factorial of a number. How to find factorial of a number using recursion in C program. Logic to find factorial of a number using recursion in C programming
Example
Input
Input any number: 5
Output
Factorial of 5 = 120
Required knowledge
  1. First let us give a meaningful name to our function, say fact().
  2. The factorial function accepts an integer input whose factorial is to be calculated. Hence the function declaration should look like fact(int num);.
  3. The function returns factorial as an integer value. Since, factorial can grow rapidly hence the suitable return type for this function is unsigned long long.Recursive function to find factorial
    The above mathematical function defines a recursive approach to find factorial of a number.
    Factorial of 0 is 1 which is our base condition i.e. if(num == 0) return 1;. If number is positive then return product of n and factorial of n-1. To find factorial of n-1 we make a recursive function call to our factorial function i.e. num * fact(num - 1)
 Source code:
Here we have the codes!! 
#include<stdio.h>
long int multiplyNumbers(int n);
int main()
{
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %ld", n, multiplyNumbers(n));
    return 0;
}
long int multiplyNumbers(int n)
{
    if (n >= 1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}


No comments:

Post a Comment

Popular Posts

Post Top Ad

Your Ad Spot

Pages