Multiplying For Loop Challenge

Hello everyone,

I’m working on the following exercise: https://www.codecademy.com/paths/analyze-data-with-r/tracks/introduction-to-programming-in-r/modules/intro-to-programming-in-r/articles/loops-in-r

Btw., I have no background in programming and this is my first time doing any programming, so please assume that I need some dummy-level explanations.

  1. My first problem is that English isn’t my first language and I’m not 100% sure if I’m even understanding the assignment correctly. To me, “multiply all the numbers of the vector” sounds like I’m supposed to calculate 1.5 x 3 x 2 x 4 x 3 x 0.25 x 3 in one step. In that case, I would be done without any extra iterations since it equals 81 already, and I feel like that can’t be right.
  2. I also don’t understand why I’m supposed to use a for loop and have a hard time to understand the general logic of a for loop here – if I don’t know how many times I’m going to repeat the code, how would a for loop be beneficial? If anything, I would use a while loop, like so:
#given information
  numbers <- c(1.5, 3, 2, 4, 3, 0.25, 3)
  product <- 1
  
#what I could do
 i <- 1
 while(product < 81) {
    product <- i*exp(sum(log(numbers)))
    if(product < 81) {
     i <- i + 1
    }
    } 
  # print result
  print(product)
  print(i)

A for loop that gets the result “81” too would be:

for (x in 1:1) {
  product <-exp(sum(log(numbers)))
}
  print(product)

But this seems less effective since I’d have to change the number of iterations by hand…
Could anyone help?

You don’t need to use the 81; I think that’s only there to help you check the answer.
You could find the length of the vector and then access each number in the vector by index.
(Finding the length tells you how many times to repeat/iterate.)

numbers <- c(4, 3, 2, 1)
product <- 1
end <- length(numbers)

for (i in 1:end) {
  product <- product * numbers[i]
}

or you could loop on all the stuff in the array directly:

numbers <- c(4, 3, 2, 1)
product <- 1

for (x in numbers) {
  product <- product * x
}

What is happening with the loop could be written like this:

# first iteration
x <- 4 # set x to be the first number in the vector
product <- product * x # multiply product by x, change product to be the result of this
# product is now 4

# second iteration
x <- 3 # set x to be the next number in the vector
product <- product * x # multiply product by x, change product to be the result of this
# product is now 12

# third iteration
x <- 2 # set x to be the next number in the vector
product <- product * x # multiply product by x, change product to be the result of this
# product is now 24

# fourth iteration
x <- 1 # set x to be the next number in the vector
product <- product * x # multiply product by x, change product to be the result of this
# product is now 24
1 Like