C++ Notes: Function Exercises 2

Name: _________________________________
  1. (3 points) Write a function named toSeconds which takes three integer parameters, a number of hours, number of minutes, and number of seconds and returns the total number of seconds. As always, use good indentation and meaningful identifier names. For example,
        cout << toSeconds(0, 2, 15);
    would print 135, the total number of seconds in 0 hours, 2 minutes and 15 seconds.









  2. (5 points) Write a complete program which reads floating point numbers from cin and prints both the maximum AND minimum values from the input. Write the answer on the back of this page.
  3. (8 points) Fill in the blanks in the following program. Each blank should either be one token (operator, identifier, punctuation mark, ...) or none (leave the space blank or put NONE in it).
        // Program to read numbers and print the second largest.
        #include <__________>
        using namespace std;
        
        int main() {
            int max1, __________;
            __________ x;
            if (cin >> max1) {
                max2 = max1;
                while (cin __________ x) {
                    if (x __________ max1) {
                        max2 = max1;
                        max1 = x;
                    }else __________ (x > max2) {
                       max2 = __________;
                    }
               }
               cout << "Second largest number = " << max2;
           }else{
               cout << "No input!";
           }
           __________ 0;
        }         
        
  4. Given the following program:
        // Program to convert hours, minutes, seconds into seconds.
        . . .  // initial program statements omitted.
        
        //----------------------------------------------------- main
        int main() {
            int hours, minutes, seconds;
            while (readRange(hours  , 0, 1000) 
                && readRange(minutes, 0,   59) 
                && readRange(seconds, 0,   59)) {
               cout << hours << ":" << minutes << ":"<< seconds << endl;
            }
            return 0;
        }//end main
        
        //----------------------------------------------------- readRange
        int readRange(int& x, int low, int high) {
            while (1) {// repeat until break or return;
                cout << "Enter an integer in the range " 
                    << low << " to " << high << endl;
                if (cin >> x) {
                    if (x < low || x > high) {
                        cout << x << " is out of range." << endl;
                    }else{
                        break;   //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                    }
                }else{
                    return 0;    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                }
            }//endwhile
            return 1;
        }//end readRange