Write a C program to Print factorial of a number. In this program, We are going to write a C program which takes an input number and print it's factorial.

To solve this problem, we are using iterative approach. If you are not familiar with iterative and recursive approach then you can check this awesome tutorial on recursion vs iteration.

Difference between iteration and recursion

Java program to print factorial of a number

#### What is Factorial?

For any input number n, it's factorial isfactorial = 1 * 2 * 3 * 4 .......n;

Suppose, An input number is 4 then it's factorial is 4 * 3 * 2* 1 = 24

## C Program to Print Factorial of a Number using Loop

In this program, we take a input number and using

**for loop**our program calculate and print the factorial of a number.

#include<stdio.h> int main() { int number, fact=1, i; printf("Enter a number \n "); scanf("%d",&number); //If a number is greater than zero if(number > 0) { for(i = 1; i <= number; i++){ fact = fact*i; } printf("The factorial of a number is: %d",fact); } else if (number == 0 ){ printf("Factorial of 0 is 1"); } else { printf("Factorial of negative number doesn't exist"; } return 0; }

## C Program to Print Factorial of a Number using Function

#include <stdio.h> //This method calculate and return factorial int factorial(int num) { int fact = 1; //Factorial of a zero is zero if (num == 0) { return 1; } for (int i = 1; i <= num; i++) { fact = fact*i; } return fact; } int main(void) { int num; printf ("Enter a number \n"); scanf ("%d", &num); if (num >= 0) { //Function is called factorial(num) printf ("Factorial of a number is %d", factorial(num)); } else { printf ("Factorial of a negative number doesn't exist"); } return 0; }

**Output -**

**Enter a number 5**

Factorial of a number is 120

Print factorial of a number using recursion

## No comments:

## Post a Comment