CSCI 160: Fall Midterm 1 SAMPLE SOLUTIONS
Sections F18N01-F18N04 (Dr. Wessels)

Question Mark
1. Write a program
[6 marks]
 
2. Write a function
[6 marks]
 
3. Show the output
[6 marks]
 
4. Show the output
[6 marks]
 
5. Fix a function
[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 of 1234567.8 illustrated in bold italics):

Please enter the distance between the planet and the sun (in km):
1234567.8
Light would take 4.11807433 seconds to travel from the sun to the planet

Sample solution
#include <cstdio>

const double SoL = 299792.5;

int main()
{
   double distance = 0;
   printf("Please enter the planet-to-sun distance\n");
   scanf("%lg", &distance);
   double time = distance / SoL;
   printf("Time taken is %.8lf\n", time);
   return 0;
}

Question 2: Write a function [6]

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

// This function computes and returns one root of a quadratic equation,
//    where coefficients a, b, and c are passed as parameters.
// The result is calculated as follows:
//    if coefficients a and b are both 0 the result is 0,
//    otherwise if a is 0 the result is -c/b
//    otherwise if b*b < 4*a*c the result is 0
//    otherwise the result is (-b + sqrt(b*b - 4*a*c))/(2*a)
double quadroot(double a, double b, double c);

Sample solution
double quadroot(double a, double b, double c)
{
   if ((a == 0) && (b == 0)) {
      return 0;
   } else if (a == 0) {
      return -c/b;
   } else if ((b*b) < (4*a*c)) {
      return 0;
   } else {
      return (-b + sqrt((b*b) - (4*a*c)) / (2*a);
   }
}

Question 3: Show the output [6]

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

#include <cstdio>

void f1(double d);
int f2(int i, int j);
double f3(long &L);
bool f4(char c, long i);

int main()
{
   int i = 4;
   long x = 10;
   double y = f3(x);
   char c = 'x';
   printf("start: c = %c, x = %ld, y = %lg, i = %d\n", c, x, y, i);
   if (f4(c, x)) {
      i = f2(i, 2*i);
   }
   f1(y);
   printf("end: c = %c, x = %ld, y = %lg, i = %d\n", c, x, y, i);
   return 0;
}

void f1(double d)
{
   printf("d = %06.3lf\n", d);
}

int f2(int i, int j)
{
   printf("i = %d, j = %d\n", i, j);
   return (i+j);
}

double f3(long &L)
{
   L = 3 * L;
   printf("L = %05ld\n", L);
   return (L / 2.0);
}

bool f4(char c, long i)
{
   printf("c = \"%c\", i = %ld\n", c, i);
   if (c != 'Q') {
      return true;
   }
   return false;
}

Sample solution
L = 00030
start: c = x, x = 30, y = 15, i = 4
c = "x", i = 30
i = 4, j = 8
d = 15.000
end: c = x, x = 30, y = 15, i = 12
Explanations
from f3
from main, note f3 was pass by ref, so value of L went in x
from f4, inside double-quotes, the \" prints ", value of x was passed to parameter i
from f2
from f1, the 6 is the total width of what's displayed, including the .
from main, note that f2 returned 12, that's what's in i now

Question 4: Show the output [6]

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

#include <cstdio>

void s(double &a, double &b, double &c);

int main()
{
   double x, y, z;
   x = 1;
   y = 2;
   z = 3;
   s(x, y, z);
   printf("x = %lg, y = %lg, z = %lg\n", x, y, z);

   x = 3;
   y = 2;
   z = 1;
   s(x, y, z);
   printf("x = %lg, y = %lg, z = %lg\n", x, y, z);
   return 0;
}

void s(double &a, double &b, double &c)
{
   double g = a;
   double h = b;
   double i = c;
   if (a > b) {
      printf("case 1:  %lg, %lg, %lg\n", g, h, i);
      g = b;
      h = a;
      if (b > c) {
         printf("case 1a: %lg, %lg, %lg\n", g, h, i);
         g = c;
         h = b;
         i = a;
      } else if (a > c) {
         printf("case 1b: %lg, %lg, %lg\n", g, h, i);
         h = c;
         i = a;
      }
   } else if (a > c) {
      printf("case 2:  %lg, %lg, %lg\n", g, h, i);
      g = c;
      h = a;
      i = b;
   } else {
      printf("case 3:  %lg, %lg, %lg\n", g, h, i);
      if (b > c) {
         h = c;
         i = b;
      }
   }
   a = g;
   b = h;
   c = i;
}

Sample solution
case 3:  1, 2, 3
x = 1, y = 2, z = 3
case 1:  3, 2, 1
case 1a: 2, 3, 1
x = 1, y = 2, z = 3
Explanation
from function's else case, since a < b and a < c
from main
from function's if case, since a > b
now the b > c case within that, since b > c
from main

Question 5: fix a function [6]

The error checking in the function below does not match the specifications shown in the comments. Alter the error checking (not the comments) so it does carry out error handling correctly.

// get the user to supply their age as an integer
//     in the range min to max (inclusive)
//     and return the value
// if an invalid value is given, print an appropriate
//     error message and give them one more chance,
//     if the second value is also invalid return -1
int getAge(int min, int max)
{
   printf("Please enter your age as an integer in the range %d-%d\n", min, max);
   int age = -1;
   int count = scanf("%d", &age);
   if (age < min) {
      printf("Error: %d < %d, please try again\n", age, min);
   } else if (age > max) {
      printf("Error: %d > %d, please try again\n", age, max);
   } else if (count < 0) {
      printf("Error: that was not an integer, please try again\n");
      scanf("%*s");
   } else {
      return age;
   }
   printf("Please enter your age as an integer in the range %d-%d\n", min, max);
   scanf("%d", &age);
   return age;
}

Sample solution
Three issues to fix
(i) should be (count < 1), not (count < 0)
(ii) the (count < 1) test needs to be the first test,
     before checking if age is < min or > max
(iii) the error checking needs to be repeated for the second scanf

int getAge(int min, int max)
{
   printf("Please enter your age as an integer in the range %d-%d\n", min, max);
   int age = -1;
   int count = scanf("%d", &age);
   if (count < 1) {
      printf("Error: that was not an integer, please try again\n");
      scanf("%*s");
   } else if (age < min) {
      printf("Error: %d < %d, please try again\n", age, min);
   } else if (age > max) {
      printf("Error: %d > %d, please try again\n", age, max);
   } else {
      return age;
   }
   printf("Please enter your age as an integer in the range %d-%d\n", min, max);
   count = scanf("%d", &age);
   if (count < 1) {
      printf("Error: that was not an integer, please try again\n");
      scanf("%*s");
      return -1;
   } else if (age < min) {
      printf("Error: %d < %d\n", age, min);
      return -1;
   } else if (age > max) {
      printf("Error: %d > %d\n", age, max);
      return -1;
   }
   return age;
}


  CSCI 160 Exam Quick Reference Sheet: Sections F18N01-F18N04

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