Exercise: The Factorial of a Number (Loops)
Let's calculate the factorial of an integer.
We'll cover the following
Problem Statement
For an integer, n
, the factorial is its product with all the positive integers before it. The factorial is denoted by the !
character.
In this exercise, you need to write the fact()
method which takes in an integer and returns its factorial. While we have already done this using recursion, you should now use the iterative approach.
Note: For
0
or1
, the factorial is always1
.
For simplicity, we do not need to cater for negative integers.
Sample Input
fact(5)
Sample Output
120
Coding Challenge
Think carefully about the logic behind the algorithm before jumping on to the implementation. This problem shouldn’t be too hard if you understand the basics of loops.
If you feel stuck, you can always refer to the solution review in the next lesson.
Good luck!
Get hands-on with 1400+ tech skills courses.