Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Wednesday 27 March 2019

Factorial Algorithm

ALGORITHM F(n)

//Computes n! recursively

//Input: A nonnegative integer n

//Output: The value of n!

if return 1

else return F (n 1 n

program:


#include <stdio.h>
 int factorial(int c){
     if(c==1){
        return 1;
     }
     else{
 return c*factorial(c-1);
 }
 }
int main()
{
  int c, n, fact = 1;

  printf("Enter a number to calculate its factorial\n");
  scanf("%d", &n);
  fact=factorial(n);

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

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

  return 0;
}

Output:

Enter a number to calculate its factorial
5
Factorial of 5 = 120

0 comments:

Post a Comment