This blog is under construction

Sunday 7 July 2013

C program to calculate factorial

Write a C program to calculate factorial.


  #include <stdio.h>

  int main() {
        int num, result = 1, i;

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

        /* 1! or 0! is 1 */
        if (num == 0 || num == 1)
                printf("%d! = %d\n", num, 1);

        /* finding factorial for the given input */
        for (i = num; i > 0; i--) {
                result = result * i;
        }

        /* print the result */
        printf("%d! = %d\n", num, result);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for num:5
  5! = 120





See Also:

No comments:

Post a Comment