What does the flowchart look like?
Ready to draw?
No signup. Opens instantly in your browser.
What is the matching code?
Pseudocode
read n
if n < 0 then refuse
result = 1
i = 1
while i <= n
result = result * i
i = i + 1
return resultPython
def factorial(n):
if n < 0:
raise ValueError("negative")
result = 1
i = 1
while i <= n:
result *= i
i += 1
return resultC
unsigned long long factorial(int n) {
unsigned long long result = 1;
int i;
if (n < 0) return 0;
for (i = 1; i <= n; i++) result *= (unsigned long long) i;
return result;
}- For n = 0 the loop test 1 <= 0 fails immediately, so the result stays 1.
- For n = 4 the multiplications are 1, 2, 3, and 4, which is 24.