Why my code prints out 3 values instead of 2 (if I am right), given what pseudo-code I have
function multiply(arr, n) {
//extract the first element of the arr
var product = arr[0];
for (var i = 1; i <= n; i++) {
//iterate over i starting from 1 unless it is less than equal to n
//n = 3
//1 , 1 <= 3 //false
//2 , 2 <=3 //false
//3 , 3 <= //true
console.log(arr[i])
//product *= arr[i];
}
//return product;
}
console.log(multiply([1,2,5,6,7,8], 3));
//output 2,5,6
It is part of this, where I m trying to understand what the example says.
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36.
It prints 3 values because your if statement says to start counting from 1 and keep going until it reaches 3.
Therefore, when we count from 1 to 3 we say: 1, 2, 3
That’s three things.
If you want it to print 2 things you can say to count from 1 to less than 3 which is the same as 1, 2 for example. Or you can just pass it 2 into the parameter ‘n’.
The i <=n in your loop means “keep doing this as long as i <= n is true”. 1 <= 3 is true. The loop executes. 2 <= 3 is true. The loop executes. 3 <= 3 is true. The loop executes. 4 <= 4 is false. The loop exits.
What do you mean by you can’t run it? What part of the example code do you not understand?
function multiply(arr, n) {
// assign first array element to product
var product = arr[0];
// loop n times starting at 1
for (var i = 1; i <= n; i++) {
// multiply product with the current array element, using shorthand
// same as product = product * arr[i];
product *= arr[i];
}
return product;
}
console.log(multiply([2, 3, 4], 2));
// 24
// 2 * 3 === 6
// 6 * 4 === 24
Not sure if this example is super helpful, but it might at least show the use of the n parameter in a different context.
function inviteGuests(guests, numberOfGuests) {
// Let make sure we have at least one guest, otherwise it is a lame party
let guestList = guests[0];
// loop numberOfGuests times starting at 1
for (let i = 1; i < numberOfGuests; i++) {
// Do some string concatenation
guestList += ', ' + guests[i];
}
return guestList;
}
console.log(inviteGuests(['Jack', 'Matt', 'Jenny', 'Paula', 'Benny', 'John', 'Anna'], 2));
// Jack, Matt
console.log(inviteGuests(['Jack', 'Matt', 'Jenny', 'Paula', 'Benny', 'John', 'Anna'], 4));
// Jack, Matt, Jenny, Paula
console.log(inviteGuests(['Jack', 'Matt', 'Jenny', 'Paula', 'Benny', 'John', 'Anna'], 6));
// Jack, Matt, Jenny, Paula, Benny, John