CSCI 160: Fall Final Midterm 1 Sample Solutions
Sections F16N01-F16N04 (Dr. Wessels)

Question Mark
1. Write a program
[7 marks]
 
2. Write a function
[7 marks]
 
3. Show the output
[7 marks]
 
4. Fix a program
[7 marks]
 
5. Modify a function
[7 marks]
 
Exam Total

[35 marks]

 

 

Question 1: Write a program [7]

Write a complete and correct C++ program that meets the following specifications:

A sample run of the program is shown below, with the user input (1.21, 4, and 3 in this case) shown in bold italics:

Please enter a number
1.21
The square root of 1.210000 is 1.100000
Please enter two numbers
4
3
4.000000 to the power of 3.000000 is 64.000000

SAMPLE SOLUTION
#include <cstdio> #include <cmath> int main() { printf("Please enter a number\n"); double x; scanf("%lf", &x); double root = sqrt(x); printf("The square root of %lf is %lf\n", x, root); printf("Please enter two numbers\n"); double y, z; scanf("%lf", &y); scanf("%lf", &z); double power = pow(y, z); printf("%lf to the power of %lf is %lf\n", y, z, power); return 0; }

Question 2: Write a function [7]

A function description and prototype are provided below. Write the full version of the function.

// This function computes and returns the volume of a pyramid,
//    where the length, width, and height are provided via parameters
//    and volume is computed using the formula:
//       volume = (length * width * height) / 3
// error handling: none required
double pyrVolume(double length, double width, double height);

SAMPLE SOLUTION
double pyrVolume(double length, double width, double height) { double volume = 0; volume = (length * width * height) /3; return volume; } // note that the body could be simplified to one line, e.g. double pyrVolume(double length, double width, double height) { return (length * width * height)/3; }

Question 3: Show the output [7]

Show the complete and precise output the following program would produce on the screen during execution.

#include <cstdio>

void f1(int x, int &y);
int  f2(int a);
int f3();

int main()
{
    int m = 2;
    int n = f2(m);
    f1(m, n);
    printf("in main, m is %d, n is %d\n", m, n);
}

void f1(int x, int &y)
{
   printf("in f1, x is %d, y is %d\n", x, y);
   y = y + 1;
}

int  f2(int a)
{
   int b = f3();
   a = a + 1;
   b = a * b;
   printf("in f2, a is %d, b is %d\n", a, b);
   return b;
}

int f3()
{
    int i = 10;
    printf("in f3, i is %d\n", i);
    return i;
}

SAMPLE SOLUTION
in f3, i is 10 in f2, a is 3, b is 30 in f1, x is 2, y is 30 in main, m is 2, n is 31
Explanation: (1) main sets m to 2 then calls f2(m), i.e. passing value 2 to f2 (2) f2 puts the value 2 (copied from m) into parameter a, then calls f3 (no parameters are passed to f3) (3) f3 sets it local variable i to 10, and prints the message in f3, i is 10 then it returns value 10 to f2 (4) back in f2, picking up where we left off the return value (10) is stored in b parameter a is set to its old value plus 1, i.e. a is now 3 variable b is set to its old value times a, i.e. 10*3, or 30 f2 now displays its print message in f2, a is 3, b is 30 f2 then returns the value in b, 30, to the main routine (5) back in main, picking up where we left off the return value, 30, is stored in n main then calls f1, passing the values in m (2), and n (30) (6) in f1, x has the value 2 (copied from m) and y has value 30 (copied from n) f1 displays its print message in f1, x is 2, y is 30 it then changes y to 31, and since y is pass by reference that changes n in main (7) control then returns to the main routine and the main routine prints m and n (with the new value for n) and ends (return 0)

Question 4: Fix a program [7]

The program below currently does not behave as its comments indicate it should (a sample run of the 'broken' program is shown below, followed by the output it should have produced).

Fix the code to match the comments provided. (Feel free to write your changes directly on the code below, you do not have to rewrite the entire program.)

// This program prompts the user to enter three positive numbers,
//    reads the three values the user enters,
// and computes and displays the sum of any positive numbers entered.
// (i.e. it ignores anything that isn't a number and ignores
//     anything that is 0 or less).

#include <cstdio>

// this function prompts the user to enter a positive number,
//    reads it, and returns it,
// the function returns 0 if the user entered something that
//    wasn't a number or was 0 or less
double getPosNumber();

int main()
{
   // get the three user values (0's replace negative or non-numbers)
   double firstVal = getPosNumber();
   double secondVal = getPosNumber();
   double thirdVal = getPosNumber();

   // compute and display the sum of the three returned values
   double sum = firstVal + secondVal + thirdVal;
   printf("Of the three things you entered, the sum of the positive numbers is %g\n", sum);
}

double getPosNumber()
{
   // prompt the user and read their response
   double userVal;
   printf("Please enter a positive number\n");
   scanf("%lf", &userVal);

   // if the user entered garbage, discard the value and return 0,
   // otherwise if the user entered a value of 0 or less, return 0,
   // otherwise return the value they entered
   return userVal;
}

// output of sample run, user input is shown in bold italics Please enter a positive number -3 Please enter a positive number foo Please enter a positive number Of the three things you entered, the sum of the positive numbers is -9 (NOTE: it didn't even give the user a chance to enter a third value...)
// what the output should have looked like if the program wasn't broken Please enter a positive number -3 Please enter a positive number foo Please enter a positive number 10 Of the three things you entered, the sum of the positive numbers is 10

SAMPLE SOLUTION
// Note the only changes are in the getPosNumber function, so only that is shown here double getPosNumber() { // prompt the user and attempt to read their response double userVal; printf("Please enter a positive number\n"); int scanResult = scanf("%lf", &userVal); // if the user entered garbage, discard the value and return 0 if (scanResult == 0) { scanf("%*s"); return 0; } // if the user entered a value of 0 or less, return 0 if (userVal <= 0) { return 0; } // return the value the user entered (now known to be a positive number) return userVal; }

Question 5: Modify a function [7]

The function below currently returns the smaller of its two parameters.

Modify the function to take three numeric parameters, and to return the smallest of all three.

// smaller returns the smaller of x and y
double smaller(double x, double y)
{
   if (x < y) {
      return x;
   } else {
      return y;
   }
}

SAMPLE SOLUTION
// smaller returns the smaller of x, y, and z double smaller(double x, double y, double z) { int smallest = x; if (y < smallest) { smallest = y; } if (z < smallest) { smallest = z; } return smallest; } // an alternative would be to check x, y, and z in turn, e.g. double smaller(double x, double y, double z) { // see if we should return x if ((x <= y) && (x <= z)) { return x; } // it wasn't x, it must be y or z else if (y <= z) { return y; } // it wasn't y, it must be z return z; }

 


  CSCI 160 Exam Quick Reference Sheet: Sections F16N01-F16N04

Comments:    Single line //
          or Multi-line  /* ....
                            .... */

C++ operators
=============
Arithmetic operators:     +   -   *   /   %   ++  --
Assignment operators:  =  +=  -=  *=  /=  %=
Boolean operators:     &&  ||  !  ==  !=  <=  >=  <  >

Data Types
=======================================================
Data        Keywords             Literal Examples
integers:   short, int, long     3, -200, 0
reals:      float, double        3.14, -0.0003
character:  char                 'x'
boolean:    bool                 true, false

Sample variable declarations (with/without initialization)
==========================================================
int    i;       int    i = 3;
char   c;       char c = 'Q';   char c = '\n';
bool   b;       bool b = true;

Sample constant declarations
============================
const double Pi = 3.1415;

Sample input with scanf, fgets, and getc (cstdio library)
=========================================================
// scanf returns a count of the number of variables "filled"
scanf("%c", &x);  // read a character into char variable x
scanf("%d", &i);  // read an integer into int variable i
scanf("%ld", &n);  // read an integer into long variable n
scanf("%g", &f);  // read a real number into float variable f
scanf("%s", &a);  // read text into variable a (char[])
scanf("%*s");     // read and discard the next word of input
scanf("%4d", &i); // read a maxium of 4 digits into int variable i

Sample output with printf (cstdio library)
==========================================
// printf returns a count of the number of characters printed
printf("%c", x);  // print the contents of  char variable c
printf("%d", i);  // print the contents of int variable i
printf("%ld", n);  // print the contents of long variable n
printf("%g", f);  // print the contents of float variable f
  // (%f gives fixed point, %e gives exponential notation, %g can do either)
printf("%5.2g, f); // print the contents of f with width 5, 2 decimal places

Some useful library functions and constants
===========================================
cmath
-----
double ceil(double)
double floor(double)
double fabs(double)
double log(double)
double pow(double, double)
double cos(double) // also acos, sin, asin, tan, atan
double sqrt(double)

Sample control structures
=========================
if (expr) {                  // works on short, int, long,
   .......                   //    char, or enum values
} else if (expr) {           switch (expr) {
   ........                     case value1:
} else {                            .....
   ........                         break;
}                               case value2:
                                    .....
// is X between 3 and 9?            break
if ((3 < X) && (X < 9)) {       default:
   // yes it is                     .....
} else {                            break;
   // no it isn't            };
}

(continued on other side of page)

         Sample function prototypes and implementations         Sample calls
         ==============================================         ============
void swap(int &a, int &b);      float calc(int x, float f)      int main()
......                          .....                           {
void swap(int &a, int &b)       float calc(int x, float f)         int i = 1;
{                               {                                  int j = 2;
    int temp = a;                  float result = x * f;           swap(i, j);
    a = b;                         return result;                  float f = calc(i, 2.5);
    b = temp;                   }                               }
}