This blog is under construction

Saturday 6 July 2013

C program to calculate factorial of a number using functions

Write a C program to calculate factorial of the given number using functions.


  #include <stdio.h>

  /* determines factorial for the given number */
  int factorial(int val) {
        int fact = 1, i;
        /* 0! or 1! is 1 */
        if (val == 0 || val == 1)
                return (1);

        for (i = val; i > 0; i--) {
                fact = fact * i;
        }
        return fact;
  }

  int main() {
        int input, output;

        /* get the input from the user */
        printf("Enter your input:");
        scanf("%d", &input);

        /* wrong input */
        if (input < 0) {
                printf("Wrong input!!\n");
                return 0;
        }

        /* finding factorial */
        output = factorial(input);
        printf("Factorial output: %d\n", output);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:1111
  Result: 15



No comments:

Post a Comment