C bootcamp · Lab 10

Factorial function

mediumFunctions12 minLesson: Functions

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Write a function long factorial(int n) that returns n!. 0! is 1.

main already reads n and prints the result. Fill in the function. A loop is enough — you do not need recursion.

Input. One integer n.

Output. One integer n!.

Constraints

  • 0 ≤ n ≤ 12

Examples

Example 1 — 5! = 5×4×3×2×1
Input
5
Output
120
Example 2
Input
0
Output
1
Hint
  1. Start with long result = 1; then for (int i = 2; i <= n; i++) result *= i;
  2. Return 1 immediately when n is 0 or 1.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

long factorial(int n) {
  long result = 1;
  for (int i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

int main(void) {
  int n;
  if (scanf("%d", &n) == 1) {
    printf("%ld\n", factorial(n));
  }
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.