Digital जीवन

Free Online Education for India...

Full width home advertisement

Computer Basic

C Programming

Engineering Graphics

Post Page Advertisement [Top]

Dr. A.P.J. Abdul Kalam Technical University, Lucknow

KCS151 / KCS251 Programming for Problem Solving - Using C Language


Lab Exercises


20. Write a program to find the factorial of the given number using recursion.


/*
 File: Prgrm20.c
 Author: Aditya Saini
 Date: Jan 17, 2021
 Description: Program to find the factorial of the given number using recursion.
*/

#include <stdio.h>

int factorial (int);

int main (void)
{
     int num;
     int fact;

     //Input number
     printf ("Input number: ");
     scanf ("%d", &num);

     //Function call
     fact = factorial (num);

     //Print result
     if (fact > 0)
          printf ("Factorial: %d", fact);

     return 0;
};

int factorial (int num)
{
     //Calculate factorial
     //Base case
     if (num == 1 || num == 0)
          return 1;

     else if (num >= 1)
          //Recursive call
          return num * factorial (num - 1);

     else
     {
          printf ("Error! Negative number");
          return -1;
     }
};

Output

Input number: 7
Factorial: 5040



No comments:

Post a Comment

Please do not post spam links.

Bottom Ad [Post Page]

| Designed by Colorlib