C++ bootcamp · Lab 21

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 factorial(int n) that returns n! (the product 1 × 2 × … × n). By definition 0! is 1.

main already reads n and prints factorial(n) — you only fill in the function.

Input. One line: an integer n ≥ 0.

Output. One integer: n!

Constraints

  • 0 ≤ n ≤ 20 — return a long long so large values do not overflow.

Examples

Example 1 — 1×2×3×4×5.
Input
5
Output
120
Example 2 — The empty product is 1.
Input
0
Output
1
Hint
  1. Start result at 1 and multiply by every number from 2 to n.
  2. When n is 0 or 1 the loop never runs, so result stays 1 — exactly right.
Show correct code

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

#include <iostream>

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

int main() {
  int n;
  std::cin >> n;
  std::cout << factorial(n) << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.