Skip to main content

Practical-02

Write a program to find factorial of given no using UDF.

Introduction

In this program, we will learn to write a function to calculate the factorial of a given number.

Algorithm

  1. Start
  2. Declare variables num, fact, i and initialize fact to 1.
  3. Take input from user and store it in num.
  4. Use for loop to calculate the factorial of the given number.
  5. Print the factorial of the given number.
  6. End

Code

Practical-02.c

/*Defining the function factorial which will help to calculate the factorial of given number */
int factorial(int num){
int fact = 1;
int i;

/* Here we are using loop to calculate the factorial starting from 1 to the given num*/
for(i=1; i<=num; i++){
fact =fact*i; /* multiplying each factor to get the factorial */
}
/*returns the calculated factorial*/
return fact;
}

/*Main function*/
void main(){
/*Declaring variables*/
int num;
int fact;

/*taking user input*/
printf("Enter a number: ");
scanf("%d", &num);

/*calling the factorial function*/
fact = factorial(num);

/*printing the output to user */
printf("The factorial of %d is %d",num,fact);


}

Output

Enter a number: 5
The factorial of 5 is 120
Explanation

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 5 is 12345 = 120.

In this program, we have defined a function factorial() which takes a number as an argument and returns the factorial of that number. The main() function takes the number from the user and calls the factorial() function. The factorial() function returns the factorial of the number and the main() function prints the result.