Exercises for Chapter 2

Exercises for Section 2.2

  1. Write a C++ program which uses a switch statement to determine how many days there are in a given month. The program should prompt the user to specify a month by its number (1..12), read the number from the standard input stream (cin), then print a line of output such as

    Month 9 has 30 days.

    For February, the program should print

    Month 2 has 28 or 29 days.

    Do not bother to do error-checking on the month number: you may assume that the user will enter a value in the correct range.

    Consult a C++ book or refer to the example of a switch statement in Exercise 6.33 (p. 325) to see how to specify the same action for multiple cases.

  2. The following C++ program uses a for loop to generate the perfect squares up to 100:

      #include <iostream>
      using namespace std;
      
      const int STOP_VALUE = 100;
    
      main()
      {
         int i;
         int j;
    
         cout << "The perfect squares to " << STOP_VALUE << " are:" << endl;
         for ( i = 1, j = 3; i <= STOP_VALUE; i += j, j += 2 )
            cout << i << endl;
      }
    

    However, because it is not clear that this loop is an example of definite iteration, it would be stylistically preferable to use a while loop in this example. Rewrite the program to use while instead of for.

    Note:

Exercise for Section 2.3

Revise the program in Figure 2.19 (p. 52) to use a for loop (as in Figure 2.14, p. 45) to accept 10 integers as input, storing them in an array, to sort the list of integers using bubble sort, and then to print out the sorted list. (Admittedly, this leaves only the swap function of Figure 2.19 unchanged, but the idea of ordering values is still preserved, so I guess we can say we are "revising" Figure 2.14.)

Bubble sort is a slow but cutely named sort which is useful only for sorting small lists (arrays) of values. It operates by repeatedly scanning the array of values, comparing adjacent elements and swapping them if they are out of order. It stops if no swaps were performed during the latest scan of the array.

Bubble sort can be implemented simply and elegantly by nesting a for loop inside a do loop (see Figure 2.13) and using a Boolean variable (of type bool in C++) to keep track of whether or not any exchanges (swaps) were performed by the for loop.

The for loop should scan from array index 0 to index 8 on the first pass, from 0 to 7 on the second, and so on. In some cases (Can you think of an example?), a swap will be made on every pass, so the final repetition of the for loop will "scan" from index 0 to 0 (i.e., it will only compare and possibly swap elements 0 and 1).

Since there is no example in Section 2.3 of passing an array to a function, here is what you need to know:


Copyright © 2002, 2004, 2006 Jonathan Mohr