Homework 2 - More Flow Control

Due Monday October 5, 2009 at 5:00pm.

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:
    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.

    The output should appear as follows:

    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:
    print menu to screen (cout)
    read in selection (cin)
    perform action for selection (switch)
    repeat until 0 is selected (do-while)