5.8 Exercises

  1. For each of the following subproblems, convert the given loop type (while, until) into its opposite.

    1. while (x == 5)

    2. until

      (x < 7)

    3. until

      ((x != 0) and (y > 2))

  2. Walk through the program in Example 5-8 and explain what it does.

    Example 5-8. Code for Exercise 2
        1 puts "Enter a number >= 0: "
        2 n = gets.to_i
        3 a = 1
        4 while (n > 1)
        5 	a = (n * (n - 1)) * a
        6 	n = n - 2
        7 end
        8 puts a
    
  3. Write a program to calculate compounded interest using a while loop. The user inputs the amount deposited, the interest rate (as a percentage) per period, and the number of periods the deposit accumulates interest. Compound interest means that every period, your new balance is calculated using the last period’s balance times the interest rate.

  4. Implement the mod operator without using the mod operator but using a loop. (Assume the numerator is always greater than the denominator and both are greater than 0.)

  5. Make a simple calculator. It should read in two numbers, apply an operator (+, -, *, /), and display the result. It should continue to do this until a condition of your choosing stops it.

  6. Write a program that outputs the first 20 numbers in the Fibonacci sequence. In the Fibonacci sequence, the current number is the sum of the previous two numbers. The first two numbers in the sequence are 1 and 1.

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.