C++ Exercises

Task: Write a C++ program, then compile and run, for each of the following:

  1. Ask user for two numbers and assign to num1 and num2. If num1 is larger than num2, print num1, else print num2. Save program as larger.cpp

  2. Same as exercise 1 except the program should print the smaller of the two numbers. Save as smaller.cpp

  3. Similar to exercise 10.5 at the end of chapter 10 in the book. Ask user for two numbers and assign to x and y. Ask user if they want "larger" or "smaller" number printed and assign their response to the string variable code. If x is larger than y then assign variable larger to be x and variable smaller to be y. Else assign smaller to be x and larger to be y.   If code is equal to (= =) "larger" then print larger, else print smaller.

  4. Save the program as code.cpp

  5. Same as exercise 10.6 in the book. Ask user to input a positive number N. Print message stating whether N is even or odd. Use this algorithm:


    get value for N
    while (N>0)
         N = N - 2
    if N is equal to 0
         print "even"
    else
         print "odd"

    (Don't forget to use == for is equal to)

  6. Save the program as evenodd.cpp
     
     

  7. Similar to example2b.cpp from previous exercise set. Ask for two numbers as before and store in num1 and num2. Then ask if they want to add, subtract, multiply, or divide the first by the second and store answer in string variable which.

  8. if which is equal to "add"
      print num1 + num2
    if which is equal to "subtract"
      print num1 - num2
    etc.

    (Don't forget to use == for is equal to)
    Save the program as math.cpp

  9. {Find the smallest number of a group of 10 numbers}
    int num,count,smallest;

    Ask for a whole number and store in num
    Assign smallest to be this number
    Assign count to be 1
    while (count is less than or equal to 10)
    {
        Ask for a whole number and store in num
        If this number is smaller than smallest so far then
           assign smallest to be this number
        Increment count by one
    }
    Print the smallest number
    Save the program as smallest.cpp

  10. Now change smallest.cpp so that it finds the smallest number of a list of n numbers. Ask the user "how many numbers?" and get the numbers. Print the smallest. Save the program as smallestn.cpp

  11. Now change smallestn.cpp so that it prints both the smallest and the largest numbers of a list of n numbers. Save the program as both.cpp

  12. {Print a person's name 5 times}
    {Don't forget to enclose a block of statements within curly braces}

    Ask for name and assign to name
    Assign count to be 1;
    while count is less than or equal to 5
    {
          print name
          increment count
    }
    Save program as printname.cpp