cppbeginner10 minutes
Refactor Messy Function to Calculate Factorial
Improve the readability and structure of a simple factorial calculation function in C++ without changing its behavior.
Challenge prompt
You are given a function that calculates the factorial of a number, but the code is poorly formatted and uses unclear variable names. Refactor the function to make it clean, readable, and maintainable while preserving the original functionality.
Guidance
- • Rename variables to meaningful names.
- • Use consistent indentation and spacing.
- • Replace unnecessary code with cleaner alternatives.
Hints
- • Factorial of n (n!) is the product of all positive integers from 1 to n.
- • Consider using a descriptive loop variable name.
- • Avoid redundant code such as extra conditions inside the loop.
Starter code
int fact(int n){int f=1,i=1;while(i<=n){f=f*i;i++;}return f;}Expected output
fact(5) returns 120
Core concepts
loopsfunctionsvariablescode readability
Challenge a Friend
Send this duel to someone else and see if they can solve it.