15110 SUMMER SESSION ONE - 2013

Lab 2 - Wednesday, May 22

Deliverables

  1. force.rb (demonstration)
  2. circle_area.rb (demonstration)
  3. answers.txt
  4. sphere_vol.rb
  5. factorial.rb

Place these files in a lab2 folder. Before leaving lab, zip up this folder, and hand it in.

CA Demonstration

Activities

  1. Type each of the following expressions into irb. What value do each of the following Ruby expressions evaluate to? Is that value an integer or a floating point?

    1. 250
    2. 28 % 5
    3. 2.5e2
    4. 3e5
    5. 3 * 10**5
    6. 20 + 35 * 2
      Why is this different from (20 + 35) * 2?
    7. 3.0 * 2 / 3
    8. 2 / 3 * 3.0
      Why is this different from 3.0 * 2 / 3?
    9. 25 - 5 * 2 - 9
      Is this different from ((25 - 5) * 2) - 9 and/or 25 - ((5 * 2) - 9)? Why?

    Write your answers in the file answers.txt. (Review Unit 2A lecture slides if necessary.)

  2. In sphere_vol.rb, define a Ruby function sphere_vol(r) that calculates and returns the volume of a sphere with a radius r. This can be calculated using the formula:

    \[ V = \frac{4}{3}\pi r^3\]

    Place in answers.txt a copy of irb lines in which you call sphere_vol(r) to compute the volume of sphere with a radius of 7 and irb shows you the result.

  3. In factorial.rb, define a Ruby function factorial(n) that calculates and returns n! = (1)*(2)*...*(n-1)*(n). You may assume that n is greater than or equal to 1 for this problem. HINT: You will need a variable to hold the result, initially set at 1. (Why?) Then your loop should multiply into this variable each value from 1 up to n.

    Place in answers.txt a copy of irb lines in which you call factorial(n) to compute 4!, 10! and 26! and irb shows you the result each time.