CS177/477, C++ Programming
Fall, 1999

Examination 1

Closed Book. Answer all the questions. The total points for each question or part of a question follows it in parentheses, thus: (12)

1

What is the value of the expressions a through f, below? Assume the following definitions for each one (the ASCII value of character ‘0’ is 48) (3 points each)

float f1 = 23.3;

int i1 = 5;

int i2 = 10;

short i3 = 3;

char c1 = ‘0’;

a)       f1 + i1

b)       i1 + i2 * i3

c)       i2 % i3

d)       i3 / i2 + i1

e)       f1 / i2 - i3

f)        c1 + i3

2

What is wrong with each of the following (3 points each)

a)       / keep a running total
sum += value;

b)       int Main() {
 
  int a, b = 0;
   a = b * 3;
   count << a << endl;
   return 3;
}

c)       if (x = 3)
  y = x + 1;

else
  y = x + 2;

d)       while (x > 0);
{
  x--;
  cout << x << endl;
}

e)       cout << x, y, z;

f)        int f1(x, y);

g)       class X {
public:
  void X() { a = 0; }
private:
  int a;
};

3

In the following class, which function members could serve as accessor functions (either inspectors or mutators)? (15)

class C {
private:

  int a, b;

public:

  int f1() { return a + b; }

  int f2() { return b; }

  int f3() { return f2(): }

  void f4() { a = b; }

  void f5(int x) { a = x; }

  void f6(int x, int y) { a = x; b = y; }

  void f7(int x) { a += x; }

};

4

Assume these class declarations:

class C {

private:

  int a, b;

  int p() { return a; }

public:

  int f() { return a; }

  int g() { return b; }

};

 

class D {

private:

  C c;

public:

  C f() { return c; }

};

 

and these definitions:

C x;

D y;

 

Which of the following are valid expressions (i.e. will compile) and which are invalid? (3 points each)


 


a)       x.a

b)       x.f()

c)       x.p()

d)       y.g()

e)       y.f().f()

f)        y.f().q()

g)       y.f().p()


5

Assuming that the function rand generates numbers from the sequence 7121, 45, 1072, 506, 10, 211, each time it is called, what does the following program print? Show your working to get partial credit for a wrong answer. (25)

#include <iostream>

#include <stdlib.h>

 

using namespace std;

 

class Coin {

private:

  bool HorT, last;

  int n;

public:

  Coin() {

    n = 0;

    toss();

    last = true;

    if (HorT)

      last = false;

  }

  void toss() {

    last = HorT;

    int t = rand() % 2;

    HorT = false;

    if (t == 1)

      HorT = true; // set true for heads, false for tails

    ++n;

  }

  bool getToss() { return HorT; }

  bool getLast() { return last; }

  int getN() { return n; }

};

 

int main() {

  Coin c;

  while (c.getToss() || c.getLast())

     c.toss();

  cout << c.getN() << endl;

 

  return 0;

}