Challenge 12: Computing Simple Interest

Challenge 12 is all about calculating simple interest. It asks that the program prompt for the principal, the rate as a percentage, and the amount of time. This is also a useful program, and good for working with the math operators of your language. Once again, I used Ruby. The first time through this I didn’t use the Useful Methods file, so I went back and integrated that into the file: 

require ‘../useful_methods.rb’

principal = getFloat(“Enter the principal”)

interest = getFloat(“Enter the percentage rate of interest (5% should be 5)”)

time = getFloat(“Enter the time in number of years”)

amount_accrued = principal * (1 + (interest / 100) * time)

puts “After %#.2f years at %#.2f%%, the investment will be worth $%#.2f.” % [time,interest,amount_accrued]

You’ll notice that I was able to use the odd syntax with the %#.2f and then have the individual numbers in an array after the string. 

The follow-up challenges are to make a method called calculateSimpleInterest() instead of just running through it line by line, and to have it print out the amount of money accrued after each year. I addressed it in this way:

require ‘../useful_methods.rb’

def calculateSimpleInterest()

   principal = getFloat(“Enter the principal”)

   interest = getFloat(“Enter the percentage rate of interest (5% should be 5)”)

   time = getFloat(“Enter the time in number of years”)

   1.upto(time) do |time|

       amount_accrued = principal * (1 + (interest / 100) * time)

       puts “After %#.2f years at %#.2f%%, the investment will be worth $%#.2f.” % [time,interest,amount_accrued]

   end

end

puts calculateSimpleInterest()

And the result is:

And that’s day 13 of 57!

Published by corbettbw

I am a Ruby developer in Phoenix, AZ. I'm interested in the intersection of technology and social justice, love weird science facts, and my dog, Coco; a cute black lab/pit bull mix, who won't stop eating rocks.

Leave a comment