Sunday, March 1, 2015

Function in C program to calculate factorial of a number

The C program given below is able to calculate the factorial of a number. After running the program, you will be asked to provide a number, then you will get the factorial of that.
#include<stdio.h>
int factorial(int num);

int main(){
    //declaring integer type variable
    int num;

    //displaying message to get input
    printf("Enter your number: ");
    //geting input from keyboard
    scanf("%d",&num);

    //displaying the result
    printf("Factorial of %d",factorial(num));
}

int factorial(int num) {
    //declaring integer type variables
    int i, fact=1;

    //for loop to calculate the Factorial
    for(i=1; i<=num; i++){
        fact = fact*i;
    }

    return fact;

}
 
...

No comments:

Post a Comment