Homework 2 - More Flow Control

Due Friday October 1, 2010 at 5:00pm.
NOTE: Late assignments will not be accepted beyond Saturday October 2nd. The solutions will be posted Sunday so that you can study them before the midterm on Monday October 4th.

Name your files hw2_<problem>.cpp, such as hw2_1.cpp. Email all the cpp files to my Sleipnir account.

  1. (5 points) Write a program to calculate the first n Fibonacci numbers. Recall from math the following definition of the Fibonacci sequence:
    The Fibonacci numbers Fn are defined as follows. F0 is 1, F1 is 1 and Fi+2 = Fi + Fi+1 i = 0, 1, 2, ... . In other words, each number is the sum of the previous two numbers. The first few Fibonacci numbers are 1, 1, 2, 3, 5, and 8.
    The program should prompt the user for n (the number of Fibonacci numbers) and print the result to the screen. If the user enters an invalid value for n (n <= 0), print an error message and ask the user to re-enter n (an input validation loop for n).

    The output should be similar to the following:

    Enter the number of Fibonacci numbers to compute: 3
    The first 3 Fibonacci numbers are:
    1 1 2
    
  2. (5 points) Write a program that finds and prints all of the prime numbers less than 200. You will need nested for loops for this problem. The outer loop will count from 1 to 200 while the inner loop checks if that number is a prime (and prints out the number if it is). Think about the nature of factoring to see if you can find the more optimal range for the inner loop than just checking the modulo of the numbers smaller than the number being tested.
  3. (10 points) Create a simple menu program that supports the following options:
      Welcome to the CS221 Homework 2 Menu
      ====================================
      1.  Multiply two integers
      2.  Divide two integers
      3.  Check if a number is within the range 10-20
      4.  Find the minimum of a list of 3 numbers
    
      0.  Exit
      ====================================
      Enter selection:
    
    Use the switch statment to implement the menu options. Within each case for the menu option, do the corresponding menu item. For example, in case 1, you would ask for two integers, multiply them and print the result of the multiplication to the screen. Embed the switch statement and the menu output inside a do-while statement. The pseudocode is:
    start of do-while:
      print menu to screen (cout)
      read in selection (cin)
      perform action for selection (switch)
    repeat until 0 is selected (Boolean for do-while)