Friday, May 28, 2021

Javascript Practice 67: JS Hero - while loop

 
Question: 

Write a function spaces that takes a natural number n and returns a string of n spaces.

Example: spaces(1) should return ' '.





Answer: 

function spaces (num) {

  let mySpaces = '';

  while (num-- > 0)

    mySpaces += ' '; 

  return mySpaces;

};




> declare a function spaces
> it has 1 parameter 'num'
> declare a variable mySpaces
> initialize it with an empty string
> we use a while loop as we need to repeat an action multiple times
> in this case we need to add blank spaces to a string 
> our '''empty spaces string''' will be stored in the variable mySpaces
> blank spaces will be equal to the 'num' parameter, which is fed when the function 'spaces' is called
> while loops have: a condition and a code (loop body) 
> our condition is to ensure that the code should execute as long as the num is greater than 0
> our condition is (num-- > 0)
> our code is: mySpaces += ''
> so if our function is called with the following parameter then how would this while loop work
>> spaces (3)
>> first it will check if 3 > 0; which it is and it will execute the code
>> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (1 space)
>> then since we have used the num as a counter (num--), the loop will reduce 1 from 3 = 2
>> it will check if 2 > 0; which it is and it will execute the code
>> mySpaces = mySpaces + ' '; the result in variable mySpace will now be '  ' (2 spaces)
>> then since we have used the num as a counter (num--), the loop will reduce 1 from 2 = 1
>> it will check if 1 > 0; which it is and it will execute the code
>> mySpaces = mySpaces + ' '; the result in variable mySpace will now be '   ' (3 spaces)
>> then since we have used the num as a counter (num--), the loop will reduce 1 from 1 = 0
>> it will check if 0 > 0; which it is not and it will only execute the code after the while loop
>> we return the mySpaces variable which will give us the final result

No comments:

Post a Comment