Last active
July 8, 2016 22:31
-
-
Save JRizzle88/f6c72f075948e787682cb800868f36ac to your computer and use it in GitHub Desktop.
A small Ruby program that returns the value of given position in a Fibonacci sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ask the user what position | |
puts "What position of a Fibonacci sequence would you like to see the value of? (Ex: position 6 = 8)" | |
# method for returning the value of a position in a Fibonacci sequence | |
def fibo_it(num) | |
num <= 1 ? num : fibo_it(num - 2) + fibo_it(num - 1) | |
end | |
# get the user input and convert to integer | |
pos = gets.chomp.to_i | |
# verify the user input is greater than 1 and not a string "abc" | |
if pos > 1 | |
# get the value returned by method fibo_it(num) | |
val = fibo_it(pos) | |
# output pos and val to the user | |
puts "The value of position #{pos} in the sequence is #{val}." | |
else | |
# output error | |
puts "Position must be an integer and greater than 1" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment