Colgate University, COSC101, Exam I, Spring 2002

P- 1

Name:

I.) (20 points) Consider the following declarations:

int i =1,j=2,k=3;

double r=1.5;

string str="cosc101", zero="0", one="1";

bool t=true, f=false;

Consider the following expressions. Determine their types and values.

Expression / Type / Value
1 / str.length() / int / 7
2 / str.substr(4,2) / string / “10”
3 / one = str.substr(5,1) / string / “0”
4 / t == (zero != str.substr(4,1)) / bool / true
5 / (k*5)%3 / int / 0
6 / r += i / double / 2.5
7 / i+r*i / double / 2.5
8 / i = i+r*i / int / 2
9 / r/(k/j) / double / 1.5
10 / j = k/r / int / 2

II.) (10 points) What will be the print out of the following statements?

int a,b=1;

a = b = ((b++)+3);

if (a == b)

cout < "The values of a and b are " < a < ", " < b;

else

cout < "The value of a is " < a < " and b is " < b;

The value of a is 4 and b is 5


III.) (15 points) Consider the following C++ program. What will be the output of the program on the screen?

#include <iostream>

#include <string>

using namespace std;

string Print_Is()

{

cout < " Is ";

return "";

}

int Add(int i, int j)

{

cout < i < " + " < j < Print_Is();

return i+j;

}

void main()

{

cout < " The Value " < Add(2,5) < endl;

}

Is 2 + 5 The Value 7

IV.) (15 points) Consider the following C++ function.

double f(double base, int expo)

{

double r=1;

while (expo >= 1)

{

if (expo % 3 == 1)

r *= base;

if (expo % 3 == 2)

r *= (base*base);

base *= (base*base);

expo /= 3;

}

return r;

}

What are the values of f(5,0), f(3,5) and f(2,8)?

1, 35, 28


VI.) (20 points) Write a C++ function void rect(int s) such that rect(s) will print out an s by s square of space characters surrounded by *. For example:

*****

* *

* *

** * *

** is printed by calling rect(0), ***** by rect(3).

void rect(int s)

{

int i,j;

for (i=0; i<=s+1; i++) cout < “*”;

cout < endl;

for (i=0; i<s; s++)

{

cout < “*”;

for (j=0; j<s; j++) cout < “ ”;

cout < “*” < endl;

}

for (i=0; i<=s+1; i++) cout < “*”;

cout < endl;

}


V.) (20 points) Write a C++ function int maxdiff(int a, int b, int c) such that maxdiff returns the difference of the biggest and smallest numbers of the three parameters.

For example, maxdiff(2,5,8)=6, maxdiff(8,1,3)=7, maxdiff(0,4,3)=4.

void maxdiff(int a, int b, int c)

{

int max=a, min=a;

if (max < b) max=b;

if (max < c) max=c;

if (min > b) min=b;

if (min > c) min=c;

return max-min;

}