Home > Backend Development > C++ > body text

Factorial program in C program

王林
Release: 2023-09-09 11:17:02
forward
1129 people have browsed it

Factorial program in C program

Given with the number n the task is to calculate the factorial of a number. Factorial of a number is calculated by multiplying the number with its smallest or equal integer values.

Factorial is calculated as −

0! = 1
1! = 1
2! = 2X1 = 2
3! = 3X2X1 = 6
4! = 4X3X2X1= 24
5! = 5X4X3X2X1 = 120
.
.
.
N! = n * (n-1) * (n-2) * . . . . . . . . . .*1
Copy after login

Example

的中文翻译为:

示例

Input 1 -: n=5
   Output : 120
Input 2 -: n=6
   Output : 720
Copy after login

There are multiple methods that can be used −

  • Through the loops
  • Through recursion which is not at all effective
  •  Through a function

Given below is the implementation using functions

Algorithm

Start
Step 1 -> Declare function to calculate factorial
   int factorial(int n)
      IF n = 0
         return 1
      End
      return n * factorial(n - 1)
step 2 -> In main()
   Declare variable as int num = 10
   Print factorial(num))
Stop
Copy after login

使用C语言

例子

#include<stdio.h>
// function to find factorial
int factorial(int n){
   if (n == 0)
   return 1;
   return n * factorial(n - 1);
}
int main(){
   int num = 10;
   printf("Factorial of %d is %d", num, factorial(num));
   return 0;
}
Copy after login

输出

Factorial of 10 is 3628800
Copy after login

使用C

示例

#include<iostream>
using namespace std;
// function to find factorial
int factorial(int n){
   if (n == 0)
   return 1;
   return n * factorial(n - 1);
}
   int main(){
   int num = 7;
   cout << "Factorial of " << num << " is " << factorial(num) << endl;
   return 0;
}
Copy after login

输出

Factorial of 7 is 5040
Copy after login

The above is the detailed content of Factorial program in C program. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template