You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Recursion gives us an interesting way to write algorithms that can solve complicated problems.
3
+
4
+
// Take for example factorials which is just an integer times each of the integers below it: so 5 factorial (also written 5!) is just 5 * 4 * 3 * 2 * 1.
5
+
// If we want to write an algorithm that can calculate the factorial of any given number without using recursion, we could do something like this:
6
+
7
+
functioncalcuateFactorialWithoutRecursion(num){
8
+
lettotal=num;
9
+
letnextNumber=num-1
10
+
while(nextNumber>=1){
11
+
total=total*nextNumber;
12
+
nextNumber--// decrease the next number by 1
13
+
}
14
+
returntotal;
15
+
}
16
+
17
+
// calcuateFactorialWithoutRecursion(5) // 120
18
+
// 5 * 4 * 3 * 2 * 1 = 120
19
+
20
+
// We can write the same function this way using recursion:
21
+
functioncalculateFactorialWithRecursion(num){
22
+
if(num===1){// This step is critical. The num parameter will keep decreasing until it gets to 1.
23
+
// Once the function gets called with 1 as a parameter, the function will return without calling itself.
0 commit comments