CS401 - Self-Check Quiz #2 Solutions

Give yourself about 30 minutes to do these problems.  Try not to look at your notes or the book until you're done.  Solutions will be made available online near the end of the week.
 

Question 1:  True/False

Circle T or F for the following statements:
  1. Value parameters are "safer" to use than reference parameters. 
    • TRUE - the argument is evaluated and only the value is passed to the function. 
  2. Structs allow you to define a new type.
    • TRUE - you set up a struct, then create new variables of that type.
  3. The "return" value of a function is what it prints on the screen.
    • FALSE - anything displayed on the screen is a side-effect of the function, the return value is determined by the return statement (and it must match the promised return type stated at the beginning of the function definition).
  4. Default parameters must appear at the beginning of a function definition parameter list.
    • FALSE - they must go at the end or else calls to the function can be ambiguous.
  5. You are not allowed to use the same parameter name twice in a program with multiple functions.
    • FALSE - each function has its own local scope so there is no problem with using an identifier multiple times as a parameter name.

Question 2:  Output 

Do the following problems from the book:
  • 7.1 (p.351-2)
  • part (a)
    i = 1 j = 20 k = 3

    part (b)
    i = 1 j = 20 k = 3

  • 7.3 (p.353)
  • part(a)
    i = 30 j = 20 k = 10

    part(b)
    i = 1 j = 30 k = 3


Determine the output of the following program:
 

#include <iostream>
#include <string>
using namespace std;

bool shrinkable(int val);
void shrink(int& val);
void unshrink(int& val);
void output(int m, int n, int p);

int a=2, b=8, c=0;

int main() {
  int c=28;
  while (shrinkable(c)) {
    int a;
    a = 4;
    shrink(c);
    if (shrinkable(b)) {
      shrink(b);
      unshrink(c);
    }
    output(a,b,c);
  }
  output(a,b,c);
}

bool shrinkable(int val) {
  return (!(val%a));
}

void shrink(int& val) {
  c++;
  val = val / a;
}

void unshrink(int& val) {
  val = val * a;
}

void output(int m, int n, int p) {
  cout << m << " " << n << " " << p << " " << c << endl;
}

OUTPUT:

4 4 28 2
4 2 28 4
4 1 28 6
4 1 14 7
4 1 7 8
2 1 7 8
 

Question 3:  Short Answers

  1. Describe the difference between pass-by-reference and pass-by-value.  Give one example where you would have to have PBR because PBV is not sufficient.
    • PBV forces the argument to be evaluated before the transfer of control is done to the function.  Thus, a value is being copied into a parameter of the function.  PBR does not do this, it simply passes the address of the argument (which must be a variable, by the way) to the function allowing the function access to that variable.  In effect, any argument passed by value is safe from changes made by the function whereas any argument passed by reference is allowing the function to possibly change what that argument (variable) holds.  NOTE:  There are other differences, but this is the most fundamental of them all. 
    • The function swap() does not work with value parameters because the whole point of the function is to change what two variables hold (i.e., to swap what they hold).  Thus, PBR is required.
  2. Describe the concept of a stream and how C++ treats them.
    • A stream is a hardware-independent view of input and output devices.  You can obtain (extract) items from an input stream and you can send items to an output stream.  In C++, you can treat all streams in the same way.  That is, you can get input from the console in exactly the same way you would get input from a file stream, for example.  Similarly, you can send items to a file stream in exactly the same way you would send them to the screen.  The same manipulators and rules apply.
  3. Show how a for loop can be rewritten as a while loop.  Keep it as general as possible.
    • Just rearrange the parts of a for loop to fit the while format.

    • for (init; condition; update) {               init;
         body;                          =====>      while (condition) {
      }                                               body;
                                                      update;
                                                    }
  4. How is recursion similar to looping?  How is it different? (one similarity and one difference is sufficient)
    • They are similar because they both are a method for doing repetition.  The most fundamental difference is, of course, that recursion involves multiple calls of the same function (from within itself, meaning mulitple versions of the same function will be active at any given time), whereas looping is just the direct repetition of a specified block of code until some condition becomes false.
  5. What is function overloading?  Give an example and show a few calls to your function.
    • This is when you give multiple functions the same name.  You must give them different parameter lists so the compiler can discriminate between them.

    • // version 1
      int f(int a) {
        return (a / 2);
      }

      // version 2
      int f(int a, int b) {
        return ((a+b) / 2);
      }

      // a few calls

      result = f(9);     // version 1 called, result gets 5
      result = f(12,8);  // version 2 called, result gets 10
       

Question 4:  Write C++ code

  1. Write a prototype for a void, parameterless function called "displayMenu".
    • void displayMenu();
  2. Problems 5.10, 5.11, and 5.12 in the book.
    • int Area(int width, int height);    // OR:  int Area(int,int);
    • bool IsMathSymbol(char c);          // OR:  bool IsMathSymbol(char);
    • int GetNumber();
  3. Write a struct declaration for a book (pick about 3 or 4 fields).  Declare a few book variables and give the fields values.

  4. struct Book {
       string title;
       string author;
       int pages;
       double cost;
    };

    // some variables
    Book b1, b2;

    // some uses
    b1.title = "The Language Instinct";
    b1.author = "Steven Pinker";
    b1.pages = 494;
    b1.cost = 14.50;
    b2 = b1;
     

  5. Write a function that takes in three integer parameters and returns the largest one. 

  6. int getLargest(int a, int b, int c) {
      int largest = a;
      if (b > largest)
         largest = b;
      if (c > largest)
         largest = c;

      return largest;
    }
     

  7. Write a void function with four integer parameters such that:
    1. The first two parameters are input, representing the low and high ends of a range.
    2. The third parameter should be assigned the difference between those low and high values.
    3. The fourth parameter should get the sum of all numbers between the low and high values (inclusive).

    4. // precondition:  high > low
      void lowHighCalc(int low, int high, int &diff, int &sum) {
         diff = high - low;
         sum=0;
         for (int i=low; i<=high; i++) {
            sum += i;
         }
      }
  8. Write a function that takes in an output stream as an argument and three integers, then sends those three integers to the specified stream so that they are in a vertical column, right justified.  You may assume the integers will not exceed 4 digits in width, and there is no need to insert commas.

  9. // this uses a column width of 10
    void print3inCol(ostream &out, int a, int b, int c) {
       out << setw(10) << a << endl
           << setw(10) << b << endl
           << setw(10) << c << endl;
    }
  10. Problem 6.51 in the book:
  11. // global constant
    const double speedOfLight = 2.997925e8;

    ...

    // we use doubles to maximize the range of input and outpt of
    // this function
    //
    // return works like this:
    //
    //        1000 m         1 sec          year
    //  km X --------- X -------------- X ---------
    //         1 km       2.997925e8 m     seconds
    //   
    double DistanceToLightYears(double km) {
       const double secPerYear = 365 * 24 * 60;
       return ((km * 1000) / (speedOfLight * secPerYear));
    }
       

Last Updated: 7/2/01 by H. Chad Lane, hcl@cs.pitt.edu
© 2000-2001 Jim Skrentny, University of Wisconsin