C 语言阶乘程序



正整数 n 的阶乘是从 n 到 1 的所有值的乘积。例如,3 的阶乘是 (3 * 2 * 1 = 6)。

算法

此程序的算法非常简单 -

START
   Step 1 → Take integer variable A
   Step 2 → Assign value to the variable
   Step 3 → From value A upto 1 multiply each digit and store
   Step 4 → the final stored value is factorial of A
STOP

伪代码

我们可以为以上算法起草以下伪代码 -

procedure find_factorial(number)
   
   FOR value = 1 to number
      factorial = factorial * value
   END FOR
   DISPLAY factorial

end procedure

实现

以下是对此算法的实现 -

#include <stdio.h>

int main() {
   int loop;
   int factorial=1;
   int number = 5;

   for(loop = 1; loop<= number; loop++) {
      factorial = factorial * loop;
   }

   printf("Factorial of %d = %d \n", number, factorial);

   return 0;
}

输出

程序的输出应该是 -

Factorial of 5 = 120
mathematical_programs_in_c.htm
广告