CSCI 160: Fall Midterm 1 Sample Solutions
Sections F19N01-F19N04 (Dr. Wessels)

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

[30 marks]

 
 

Question 1: Write a program [6]

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 illustrated in bold italics):

Please enter three integers:
17 4 11
Your values (from smallest to biggest) were:
4 11 17

// Sample solution 1
#include <cstdio>

// swap exchanges the values of the two parameters passed to it
void swap(int &a, int &b);

int main()
{
   // get and store the three values
   printf("Please enter three integers:\n");
   int x, y, z;
   scanf("%d", &x);
   scanf("%d", &y);
   scanf("%d", &z);

   // first, rearrange so the smallest value winds up in x
   //    and the two bigger values wind up in y and z
   if (x > y) {
      swap(x, y);
   }
   if (x > z) {
      swap(x, z);
   }

   // now rearrange y and z if necessary
   if (y > z) {
      swap(y, z);
   }

   // display the results
   printf("Your values (from smallest to biggest) were:\n");
   printf("%d %d %d\n", x, y, z);
}

void swap(int &a, int &b)
{
   int tmp = a;
   a = b;
   b = tmp;
}
// Sample solution 2
#include <cstdio>

int main()
{
   // get and store the three values
   printf("Please enter three integers:\n");
   int x, y, z;
   scanf("%d", &x);
   scanf("%d", &y);
   scanf("%d", &z);

   // as we go, we'll figure out which is biggest, smallest, and middle
   int small, med, big;

   if (x > y) {
      if (y > z) {
         small = z; med = y; big = x;
      } else {
         if (x > z) {
            small = y; med = z; big = x;
         } else {
            small = y; med = x; big = z;
         }
      }
   } else {
      if (z < x) {
         small = z; med = x; big = y;
      } else {
         if (y < z) {
            small = x; med = y; big = z;
         } else {
            small = x; med = z; big = y;
         }
      }
   }

   // now print them in order
   printf("Your values (from smallest to biggest) were:\n");
   printf("%d %d %d\n", small, med, big);
}

Question 2: Write and call a function [6]

A function description and prototype are provided below.

(i) Write the full version of the function.

// when passed values a, b, c, and x,
//    compute and return the result of ax2 + bx + c
double evalpoly(double a, double b, double c, double x);

(ii) Show a sample call to the function, where you pass values 0.5, 2, 0.1, and 10, and store the returned value in a variable named R. (You do not need to write an entire main routine or declare R, just show the sample call.)

// Sample solution
double evalpoly(double a, double b, double c, double x)
{
    return(a*x*x + b*x + c);  // (or store the computed value in a variable and return that)
}

// sample call
R = evalpoly(0.5, 2, 0.1, 10);

Question 3: Show the output [6]

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

#include <cstdio>

const char* Q = "Q3";
const char* N = "Midt";

void inf();
void f(int &a, int &b);
int g(int v1, int v2);

int main()
{
   int x = 4;
   int y, z;
   y = 10;
   inf();
   f(x, y);
   z = g(x, y);
   printf("x: %d, y: %d, z: %d\n", x, y, z);
}

void inf()
{
   printf("This is %s %s\n", Q, N);
}

void f(int &a, int &b)
{
   int x = b;
   b = a;
   a = x;
}

int g(int v1, int v2)
{
   int res = v1 / v2;
   v2 = v2 * 2;
   printf("v1: %d, v2: %d, res: %d\n", v1, v2, res);
   return res;
}

// Sample solution
This is Q3 Midt
v1: 10, v2: 8, res: 2
x: 10, y: 4, z: 2

Explanation: - the first line comes from main's call to function inf - main then calls f(x,y) where x is 4 and y is 10, function f acts as a 'swap' function, exchanging the values of its two parameters (note the parameters are pass-by-reference, so this changes x and y from main) - main then calls g(x,y) where x is now 10 and y is now 4 inside the function, parameter v1 is 10 and v2 is 4, it computes res=v1/v2 using integer division, i.e. 2 then doubles v2 (i.e. to 8), then prints v1, v2, and res then it returns res (i.e. 2) note that g's parameters are pass-by-value, i.e. copies, so the original x,y from main do not get changed - finally, back in main, it prints x, y, and the return value from g

Question 4: Modify a function [6]

You are given the function below (assume it is part of some larger program).
// given that MaxValue is a globally defined constant,
//    getNum prompts the user to enter integer in the range 0..MaxValue,
//    reads their response and returns it,
//    returning 0 if they did not enter an integer
int getNum()
{
   int userVal = 0;
   printf("Please enter an integer in the range 0..%d\n", MaxValue);
   scanf("%d", &userVal);
   return userVal;
}

Suppose we need to change the function prototype and behaviour to be as follows:
// given MaxValue as a parameter,
//    getNum prompts the user to enter an integer in the range 0..MaxValue,
//    reads and checks their response,
//    if the response was valid then getNum
//       stores their entry in finalVal and returns true
//    otherwise it returns false (leaving finalVal unchanged)
bool getNum(int &finalVal, int MaxValue);

Write the new version of the function. (You only need to write the function, you do not need to provide a main routine, call to the function, etc.)

// Sample solution
bool getNum(int &finalVal, int MaxValue)
{
   int userval; // will hold the user's data
   int numvals; // will hold the scanf return value (1 if scanf worked, 0 if it failed)

   // prompt the user and read the response
   printf("Please enter an integer in the range 0..%d\n", MaxValue);
   int numvals = scanf("%d", &userval);

   // if the user entered a number and it was in the correct range
   //    then set finalVal and return true
   if ((numvals > 0) && (userval >= 0) && (userval <= MaxValue)) {
      finalVal = userval;
      return true;
   }

   // otherwise something was wrong, return false
   return false;
}

Question 5: Write a program [6]

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

Two sample runs of the program are shown below (with the user's input illustrated in bold italics in both examples):

Please enter a real number:
37.124
The integer portion of your value was
37

Please enter a real number: junk The value beginning with j was not a number.
Note that for the bonus mark the first run would also have displayed a message like "There were 2 digits in the integer portion of your value."

// Sample solution
#include <cstdio>
#include <cmath>

int main()
{
   // prompt the user
   printf("Please enter a real number:\n");
   float x;

   // if scanf returns a value greater than 0 then it DID read in a number,
   //    so we can try to process it
   if (scanf("%f", &x) > 0) {
      printf("The integer portion of your value was ");
      // use floor (from cmath) to round down to the nearest integer
      int integerPart = floor(x);
      // print the value with no trailing 0's (i.e. so it comes out as just the integer)
      //    and use printf's return value to see how many characters long it was
      int len = printf("%g", integerPart);
      printf("\n");
      printf("There were %d digits in the integer portion of your value.\n", len);
   }

   // otherwise scanf returned 0, i.e. the user did not type in a number
   else {
      // read the first character of whatever garbage the user typed in
      // and print the error message
      char firstch;
      scanf("%c", &firstch);
      printf("The value beginning with %c was not a number.\n", firstch);
   }
}

// Notes: this one was a little trickier on purpose,
//    the easiest solutions are
//        x = floor(x); then print with %g
//    or  printf("%d", (int)(x));
//    or  int i = x; then print with %d
//    or  to simply read it into an int in the first place,
//        e.g. int userVal;
//             scanf("%d", &userVal);
//        (although this does leave the .xxxx sitting in the input buffer)
//
//    unfortunately if you used "%.0f" to try printing
//       only the integer portion then it rounds,
//       so a value like 1.5 would come out as 2
//    and if you try to use %d to print the float then it
//       will actually come out as a seemingly irrelevant
//       and potentially huge number,
//       e.g. 1.5 with %d displays as 1533953904

  CSCI 160 Exam Quick Reference Sheet: Sections F19N01-F19N04

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
text const: const char*          "this is some text"

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
printf("%s", "Hello"); // print the contents of a text string (char*)

Some useful library functions and constants
===========================================
cmath                                    cctype
-----                                    ------
double ceil(double)                      char toupper(char) // also islower
double floor(double)                     bool isupper(char)
double fabs(double)                         // also isspace, isalpha, isdigit, etc
double log(double)
double pow(double, double)               cfloat        climits
double cos(double)                       ------        -------
  // also acos, sin, asin, tan, atan     DBL_MAX       SHORT_MAX
double sqrt(double)                      FLT_MAX       INT_MAX
                                                       LONG_MAX

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            };
}

         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;                   }                               }
}