# Generating Fibonacci and Triangular series

# Fibonacci series
# This is generated using the rule 'add the last two elements 
# together to get the next element in the series'

# Create the seed vector fib

fib<-c(1,1)

# Main loop

for (i in 2:19) {
  
  # add to the end of fib the value of fib[i]+fib[i-1]
  
  fib<-c(fib,fib[i]+fib[i-1])
}

## display fib

fib

# Triangular numbers series
# This is generated using the rule 'element[i]=element[i-1]+i'

# Create the seed vector tri

tri<-1

# Main loop

for (i in 1:19) {
  
  # Calculate number to be added to tri[i] this loop iteration
  # This will be one more than the loop index
  
  x<-i+1
  
  # Add to the end of tri the value of tri[i]+x
  
  tri<-c(tri,tri[i]+x)
}

## Display tri

tri

# Generate short forms of the vectors containing only values below 25

# We don't know how many elements we need to loop through, so
# use seq() to count through them

# Set up an empty vector to add things to

short_fib<-NULL

# For each element of fib, check to see if it is less than 25

for (i in seq(fib)) {
  
  # Copy the current element into short_fib
  
  short_fib<-c(short_fib,fib[i])
  
  # If the current element's value is over 25, stop
  
  if (fib[i]>=25) break
}

# Because we copied the element before checking it, short_fib
# now has one element too many, so we need to remove the last element

short_fib<-short_fib[-length(short_fib)]

# Display short_fib

short_fib

# Set up an empty vector to add things to

short_tri<-NULL

# For each element of tri, check to see if it is less than 25

for (i in seq(tri)) {
  
  # Copy the current element into short_tri
  
  short_tri<-c(short_tri,tri[i])
  
  # If the current element's value is over 25, stop
  
  if (tri[i]>=25) break
}

# Because we copied the element before checking it, short_fib
# now has one element too many, so we need to remove the last element

short_tri<-short_tri[-length(short_tri)]

# Display short_tri

short_tri

# At what index does tri[i] become greater than fib[i]?

# We don't know how many elements we need to loop through, so
# use seq() to count through them

for (i in seq(tri)) { # doesn't matter whether we use tri or fib
  
  # Record the value of the current index
  
  current_index<-i  
  
  # If the value of tri[i] is bigger than that of fib[i]
  # then break out of the loop

  if (fib[i]>tri[i]) break
}

## Set up a vector of strings to display the results
output<-c("Index", current_index, 
          "Tri:", tri[current_index-1], tri[current_index],
          "Fib:", fib[current_index-1], fib[current_index])

# Display the results

output
