likeliterallysoum
likeliterallysoum

Reputation: 21

Error in Repeat Loop - if/else statement problem

I'm trying to find the highest Fibonacci number before 5000. this is the code I have so far:

n <- 5000
fib <- c()
fib[1] <- 1
fib[2] <- 1
c <- 1
i <- 3
repeat {
  fib[i] <- fib[i-1] + fib[i-2]
  i <- i+1
  c <- c+1
  if (fib[i]>=5000) {
    break
  }
h <- fib[c]
print(h)
}

The error I receive is:

Error in if (fib[i] >= 5000) { : missing value where TRUE/FALSE needed

Any thoughts on how to resolve? I know my code isn't perfect, but I'm learning :)

Upvotes: 0

Views: 35

Answers (1)

dasds
dasds

Reputation: 170

you raise i before the statement: i-1 is what you want to compare. Further, this doesn't give you the highest number before 5000. So you have to execute the statement once again before break.

n <- 5000
fib <- c()
fib[1] <- 1
fib[2] <- 1
c <- 1
i <- 3
repeat {
  fib[i] <- fib[i-1] + fib[i-2]
  i <- i+1
  c <- c+1
  if (fib[i-1] >= 5000) {
    h <- fib[c]
    print(h)
    break
  }
  h <- fib[c]
  print(h)
}

Upvotes: 1

Related Questions