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

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

[35 marks]

 

Question 1: Write a program [7]

Write a complete and correct C++ program as described below.

The general purpose of the program is to determine how much space a person needs to house their horses. It will ask how many horses they want, then calculate the number of paddocks (outdoor living spaces) needed, and the total land area needed. Specifically:
1. The program begins by asking the user how many horses they want, and reads it as an integer. No error checking is required for this question.
2. It calculates and displays the minimum number of paddocks needed, assuming at most two horses can live in the same paddock.
3. It calculates and displays the total land area required, assuming 60 square metres per paddock.

Some sample runs of the program (the user input below is shown in bold italics)
Please enter the number of horses you want (e.g. 7):
10
For 10 horses you need 5 paddocks,
the total land area required is 300 square metres.

Please enter the number of horses you want (e.g. 7): 3 For 3 horses you need 2 paddocks, the total land area required is 120 square metres.
Sample solution: #include <cstdio> const int HorsesPerPad = 2; const int SqMperPad = 60; int main() { int numHorses, paddocks, area; printf("Please enter the number of horses you want (e.g. 7)\n"); scanf("%d", &numHorses); paddocks = numHorses / HorsesPerPad; // int division rounds down, so add 1 if there are leftover horses if ((numHorses % HorsesPerPad) > 0) { paddocks++; } area = paddocks * 60; printf("For %d horses you need %d paddocks,\n", numHorses, paddocks); printf("the total land area required is %d square metres.\n", area); return 0; }

Question 2: write a function [7]

Write a complete and correct C++ function that fulfills the requirements below:
1. The function is named Least, and its return type is int.
2. The function takes four int parameters, calling them a, b, c, and d (in that order)
3. The function returns the smallest of the four values passed to it.
(Thus Least(1, 3, 20, 7) would return 1, Least(18, 6, -8, 6) would return -8, etc.)
4. The function does not perform any input or output (i.e. absolutely no scanfs, no printfs).
Please do NOT write a main routine or a prototype, just the function itself.
Sample Solutions
// Version 1:
int Least(int a, int b, int c, int d)
{
   // a is the smallest seen so far
   int smallest = a;
   // see if b is even smaller
   if (b < smallest) {
      smallest = b;
   }
   // see if c is smaller than either of them
   if (c < smallest) {
      smallest = c;
   }
   // see if d is smallest of all
   if (d < smallest) {
      smallest = d;
   }
   return smallest;
}
// Version 2:
int Least(int a, int b, int c, int d)
{
   // see if a is smallest
   if ((a <= b) && (a <= c) && (a <= d)) {
      return a;
   }
   // a isn't, so see if b is smallest
   if ((b <= c) && (c <= d)) {
      return b;
   }
   // a and b aren't, so see if c is smallest
   if (c <= d) {
      return c;
   }
   // the only thing left is d
   return d;
}

Question 3: modify code segments [7]
For both parts below, assume the code segment is correctly placed within a valid C++ program.

Part I:
Re-write the code segment below to replace the switch statement with an equivalent set of if/else if/else statements. (Assume variable x has been correctly declared and set to some character value.)
switch (x) {
   case 'q':
   case 'Q':
      printf("Goodbye!\n");
      break;
   case '2':
   case '3':
   case '5':
   case '7':
      printf("Small prime\n");
      break;
   default:
      printf("Something else\n");
      break;
}

Sample solution:

if ((x == 'q') || (x == 'Q')) {
   printf("Goodbye!\n");
}
else if ((x == '2') || (x == '3') || (x == '5') || (x == '9')) {
   printf("Small prime\n");
}
else {
   printf("Something else\n");
}

Part II:
Rewrite the code segment below to make appropriate use of a constant for Pi.
circumference = 2 * radius * 3.1415;
printf("A circle with radius %lf has circumference %lf\n", radius, circumference);
area = 3.1415 * radius * radius;
printf("The circle\'s area is %lf\n", area);

Sample solution:
const double Pi = 3.1415;

circumference = 2 * radius * Pi;
printf("A circle with radius %lf has circumference %lf\n", circumference, radius);
area = Pi * radius * radius;
printf("The circle\'s area is %lf\n", area);

Question 4: Show the output [7]

Part I
For the code segment shown below, show the precise output that would be displayed on the screen when run. (Assume the code segment was correctly placed somewhere within a valid program.)
bool x = true;
bool y;
bool z = !x;

int i = 11 / 2;
if ((i < 10) && (i != 3)) {
   printf("setting y\n");
   y = true;
}
else if (i > 5) {
   printf("setting x\n");
   x = false;
}
else {
   printf("Neither is true\n");
}
if (x) {
   printf("x is true\n");
}
if (x || y || z) {
   printf("one of them is true\n");
}

Sample solution:
setting y
x is true
one of them is true

Explanation: int i = 11/2 does integer division, so sets i to 5 thus the first if statement is true (5 < 10) and (5 != 3) so it prints "setting y" and sets y to true control then moves on to the second if block, and since the if (x) condition passes, it prints "x is true" control then moves on to the final if block, and since at least one of them is true (x or y or z) it displays "one of them is true"

Part II
For the function shown below, show the precise output that would be displayed on the screen if the function was called as follows:
x = calc(3);
(Assume the call, declaration, prototype, variable x, etc were all correctly used within a program.)
int calc(int N)
{
   printf("beginning calc(%d)\n", N);
   int lesserN =calc(N-1);
   int answer = N + lesserN;
   printf("calc(%d) = %d\n", N, answer);
   return answer;
}

Sample solution:
beginning calc(3)
beginning calc(2)
beginning calc(1)
beginning calc(0)
beginning calc(-1)
beginning calc(-2)
beginning calc(-3)
beginning calc(-4)
beginning calc(-5)
... and so on and so on ...

Explanation: the call to calc(3) encounters the first printf ("beginning calc(3)") and then calls lesserN = calc(2) the call to calc(2) encounters the first printf("beginning calc(2)") and then calls lesserN = calc(1) the call to calc(1) encounters the first printf ("beginning calc(1)") etc this process continues infinitely (well, until the program runs out of memory and crashes)

Question 5: fix a program [7]

The program below contains seven simple syntax errors.

The corresponding compiler error messages are shown below the program.

Fix each of the seven errors, make it clear which fix is for which error message. (No other changes to the program should be made.)
#include <cstdio>


void calcRoots(double a, double b, double c);

int main()
{
   printf("Enter the coefficients for a degree 2 polynomial,\n);
   printf("e.g. for poly 3x^2 + 2.5x + 7 you would enter 3 2.5 7.1\n");
   double A, B, C;
   scanf("%lf", &A);
   scanf("%lf", &B);
   scanf("%lf", C);
   calcRoots(A, B);
}

void calcRoots(double a, double b, double c)
{
   if (a == 0)
      if (b == 0) {
         printf("No roots\n");
      } else {
         printf("Root is %g\n", -c/b);
      }
   } else if (b == 0) {
      if (c > 0) {
         printf("One complex root\n");
      } else {
         printf("Root is %g\n", sqrt(-c/b));
      }
   } else if (b*b < 4*a*c) {
      printf("Two complex roots\n");
   } else {
      double root1 = (-b + sqrt(b*b - 4*a*c)) / (2*a);
      double root2 = (-b - sqrt(b*b - 4*a*c)) / (2*a);
      printf("Roots are %g and %g\n", root1, root2);
   }
   return 0;
Sample Solution (changes in bold italics)
#include <cstdio>
#include <cmath>  // 1st error (sqrt)

void calcRoots(double a, double b, double c);

int main()
{
   printf("Enter the coefficients for a degree 2 polynomial,\n " ); // 3rd err (missing ")
   printf("e.g. for poly 3x^2 + 2.5x + 7 you would enter 3 2.5 7.1\n");
   double A, B, C;
   scanf("%lf", &A);
   scanf("%lf", &B);
   scanf("%lf", &C);  // 6th err (double* expected)
   calcRoots(A, B, C); // 2nd err (too few args)
}

void calcRoots(double a, double b, double c)
{
   if (a == 0) { // 7th error (ambiguous else)
      if (b == 0) {
         printf("No roots\n");
      } else {
         printf("Root is %g\n", -c/b);
      }
   } else if (b == 0) {
      if (c > 0) {
         printf("One complex root\n");
      } else {
         printf("Root is %g\n", sqrt(-c/b));
      }
   } else if (b*b < 4*a*c) {
      printf("Two complex roots\n");
   } else {
      double root1 = (-b + sqrt(b*b - 4*a*c)) / (2*a);
      double root2 = (-b - sqrt(b*b - 4*a*c)) / (2*a);
      printf("Roots are %g and %g\n", root1, root2);
   }
      // 4th error: deleted return 0 (return statement with value in void function)
} // 5th error (expected } )

SYNTAX ERRORS:

In function 'void calcRoots(double, double, double)':
29:42: error: 'sqrt' was not declared in this scope
        printf("Root is %g\n", sqrt(-c/b));

In function 'int main()': 14:18: error: too few arguments to function 'void calcRoots(double, double, double)' calcRoots(A, B);
8:11: warning: missing terminating " character printf("Enter the coefficients for a degree 2 polynomial,);
In function 'void calcRoots(double, double, double)': 38:11: error: return-statement with a value, in function returning 'void' return 0;
In function 'void calcRoots(double, double, double)': 37:4: error: expected '}' at end of input }
In function 'int main()': 13:18: warning: format '%lf' expects argument of type 'double*', but argument 2 has type 'double' scanf("%lf", C);
In function 'void calcRoots(double, double, double)': 19:7: warning: suggest explicit braces to avoid ambiguous 'else' if (a == 0) 25:6: error: expected unqualified-id before 'else' } else if (b == 0) {
  CSCI 160 Midterm1 Quick Reference Sheet: Sections F16N01-F16N04
Comments:    Single line //       or Multi-line  /* ....
                                                    .... */
C++ operators
=============
Arithmetic operators:     +   -   *   /   %   ++  --
Assignment operators:  =  +=  -=  *=  /=  %=
Boolean operators:     &&  ||  !  ==  !=  <=  >=  <  >

Data        Keywords             Literal Examples    Special values
========================================================================================
integers:   short, int, long     3, -200, 0          INT_MAX, INT_MIN  (climits library)
reals:      float, double        3.14, -0.0003       FLT_MAX, FLT_MIN  (cfloat  library)
character:  char                 'x'                 \'  \"  \\  \t \n  \0
boolean:    bool                 true, false

Sample variable and constant declarations
=========================================
int    i;       float f = 1.5;  double d = 216.013;
char   c;       char c = 'Q';   char c = '\n';
bool   b;       bool b = true;  bool b = false;
const double Pi = 3.1415;

Sample input with scanf, fgets, and getc (cstdio library)
=========================================================
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("%[abc]", &x); // read an a, b, or c into variable x
scanf("%*[\t\n]%c", &x); // skip 1 or more tabs newlines then read next char into x
scanf("%4d", &i); // read a maxium of 4 digits into int variable i

Sample output with printf (cstdio library)
==========================================
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, "prettier"
printf("%5.2g, f); // print the contents of f with width 5, 2 decimal places
printf("%s", a);  // print the contents of character array a
printf("The value of %d times %g is %g\n", i, f, (i*f));  // combined example

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

Sample function prototype with a pointer passed by reference
============================================================
void doSomething(int* &ptr);

Some useful library functions and constants
===========================================
cctype                 cfloat                   cmath
------                 ------                   -----
bool isalpha(char)     FLT_MIN, FLT_MAX         double ceil(double)
bool isalnum(char)     DBL_MIN, DBL_MAX         double floor(double)
bool isdigit(char)                              double fabs(double)
bool islower(char)     climits                  double log(double)
bool isupper(char)     -------                  double pow(double, double) 
bool ispunct(char)     CHAR_MIN, CHAR_MAX       double cos(double)
bool isspace(char)     SHORT_MIN, SHORT_MAX     // also acos, sin, asin, tan, atan
char tolower(char)     INT_MIN, INT_MAX
char toupper(char)     LONG_MIN, LONG_MAX