Help with Loops in R Exercise - While Loops

Hi Everyone,

I’m really struggling with the While loops exercise in the Loops in R section. I can’t get my head around how to link the vector into the loop and I’m also confused about what number[i] means.

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

This is what I have so far but I know it’s very wrong!

while (i < 6) {
product <- product * i
}

Thanks!

Hello, @blog4031220991, and welcome to the forums.

Is this what you’re working on?

If so, you need to access elements of the numbers vector by their index as indicated in the instructions. You can do so, like this:

somenums <- c(5, 10, 15, 20, 25)
print(somenums[1]) #prints: 5
print(somenums[4]) #prints: 20
print(somenums[2] * somenums[5]) #prints: 250

The condition for your while loop needs to test whether the element of the vector at the current index is equal to 5 (or not equal rather).

hint
i <- 1

while(numbers[i] != 5) {
  #do stuff
  #don't forget to add 1 to i inside the loop
  #otherwise, it will run forever (infinite loop)
}
1 Like