Wednesday, May 26, 2021

Javascript Practice 65: JS Hero - Factorial

 
Question: 

Write a function factorial that calculates the factorial of a positive integer.

Example: factorial(3) should return 6.




Answer: 

function factorial (num) {

let product = 1; 

for (let i = 1; i <= num; i++) {

product = product * i } 

return product
}




> we declare a function factorial
> it has one parameter 'num' 
> we first declare a variable 'product' with a value of 1
> we then open the 'for' loop 
>> let us assume that we call the factorial function with number 3 as a 'num' parameter
>> first expression: let i = 1
>> second expression or condition: i <= num
>> third expression: i++ (i++ is identical to i = i + 1)
>> loop code: product = product * i
>> in the start expression ' i ' is initialized with a value of 1 
>> the loop condition is i <= num (3);
>> if ' i ' is less than or equal to the num then the loop code is executed (1 <= 3)
>> the product variable shall receive the value of product * i or (1 * 1 = 1)
>> in the final or third expression i is increased by 1 (1 + 1 = 2)
>> ' i ' thus receives the value 2
>> the second loop starts with the evaluation of the loop condition
>> the condition 2 <= 3 is fulfilled
>> the loop code is executed again and product is now given the value (1 * 2 = 2)
>> in the final or third expression i is increased by 1 (2 + 1 = 3)
>> ' i ' thus receives the value 3
>> the second loop starts with the evaluation of the loop condition
>> the condition 3 <= 3 is fulfilled
>> the loop code is executed again and product is now given the value (2 * 3 = 6)
>> in the final expression ' i ' is increased again and gets the value  (3 + 1 = 4)
>> the second loop starts with the evaluation of the loop condition
>> the condition 4 <= 3 is no longer fulfilled
>> the loop is terminated and the program execution continues after the loop 
>> in this case the program executes and returns the 'product' variable to us
>> our code example has multiplied all natural numbers smaller or equal to 3

No comments:

Post a Comment