Q:

Fibonacci sequence less than 1000 in R

I'm trying to print the Fibonacci Sequence less than 1000 using while loop in R.
So far,
fib <- c(1,1)
counter <-3
while (fib[counter-1]<1000){
  fib[counter]<- fib[counter-2]+fib[counter-1]
  counter = counter+1
}
fib

I have this code. Only the first two numbers are given: 1,1. This is printing:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

How do I fix my code to print only less than 1000?

A:

Instead of checking the value of the last element wrt 1000, for the expected output you should be checking the sum of the last two elements as so.
fib <- c(1,1)
counter <-3
while (fib[counter-2]+fib[counter - 1]<1000){
  fib[counter]<- fib[counter-2]+fib[counter-1]
  counter = counter+1
}
fib

