CSCI 160: Fall Midterm 2 Sample Solutions
Sections F17N01-F17N04 (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 function
[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 shown in bold italics:

please enter two numbers
wrong 1
that was not two numbers, please enter two numbers
2 bad
that was not two numbers, please enter two numbers
really wrong
that was not two numbers, please enter two numbers
400.1 1.5
400.1 * 1.5 = 600.15
Sample Solution:
#include <cstdio>

int main()
{
   double x,y;
   int count1, count2;
   do {
      printf("please enter two numbers\n");
      count1 = scanf("%lg", &x);
      if (count1 != 1) {
         scanf("%*s");
      }
      count2 = scanf("%lg", &y);
      if (count2 != 1) {
         scanf("%*s");
      }
      if ((count1 + count2) != 2) {
         printf("That was not two numbers, ");
      }
   } while (!count1 || !count2);
   double result = x * y;
   printf("%lg * %lg = %lg\n", x, y, result);
   return 0;
}

Question 2: Write a function [7]

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

// frequency takes a null-terminated character array as its first parameter,
//    and a target character as its second parameter
// the function counts and returns the number of times the target character
//    appears in the array, e.g. frequency("some strings", 's'); returns 3
// (the function does NOT produce any output)
long frequency(char arr[], char target);
Sample Solution:
long frequency(char arr[], char target)
{
   long count = 0;
   long pos = 0;
   while (arr[pos] != '\0') {
      if (arr[pos] == target) {
         count++;
      }
      pos++;
   }
   return count;
}

Question 3: Show the output [7]

Part 1. Show the complete and precise output that would be produced on the screen during execution if a program performed the function call
    display(6);
(assuming the call was part of a larger valid program).

void display(int max)
{
   int sum = 0;
   for (int i = 2; i <= max; i++) {
       printf("%d: ", i);
       for (int j = 1; j <= i; j++) {
           int m = i % j;
           printf("%d,", m);
           sum = sum + j;
       }
       printf("sum = %d\n", sum);
   }
}

Part 2. Repeat the question, but this time using the call
    display(0);
Sample Solution:
// display(6)
2: 0,0,sum = 3
3: 0,1,0,sum = 9
4: 0,0,1,0,sum = 19
5: 0,1,2,1,0,sum = 34
6: 0,0,0,2,1,0,sum = 55

// display(0) produces no output at all,
//    since i <= max fails the very first time

Question 4: Fix a function [7]

The function below is broken in two ways:
(i) it gets stuck in an infinite loop,
(ii) its total is not updating correctly.

Both issues are caused by small, simple mistakes. Identify and fix the two mistakes. (Assume the cmath library has been included.)

// sums integer powers of 2 until one of them exceeds
//      the specified maximum value
// at the end it returns the total sum
double sumPowers(double max)
{
   double total = 0;
   double result = 0;
   double current = 0;
   bool again = true;

   do {
      // compute the current power of 2 and add it to the total
      result = pow(2, current);
      double total = total + result;

      // see if the stopping point has been reached
      if (result > max) {
         again = false;
      } else {
         current++;
      }
   } while (again = true);

   return total;
}
Sample Solution:
// sums integer powers of 2 until one of them exceeds
//      the specified maximum value
// at the end it returns the total sum
double sumPowers(double max)
{
   double total = 0;
   double result = 0;
   double current = 0;
   bool again = true;

   do {
      // compute the current power of 2 and add it to the total
      result = pow(2, current);
      total = total + result; // removed double

      // see if the stopping point has been reached
      if (result > max) {
         again = false;
      } else {
         current++;
      }
   } while (again == true); // used to be =

   return total;
}
// explanation:
// (1) the while condition was using "again = true" instead of "again == true",
//     which was setting the conditon to true rather than testing it
// (2) the "double total = ..." was creating a local variable named total
//     inside the loop, instead of the original variable declared for the
//     function.  This local total was disappearing at the end of each pass
//     through the loop, not continuing across all the iterations.

Question 5: Modify a function [7]

Rewrite the function below to use a loop rather than recursion to control its repetition, but still eventually calculating and returning the same final answer.

int S(int n)
{
   int x, result;
   if (n < 1) {
      result = 0;
   } else {
      x = S(n-1);
      result = x + n*n;
   }
   return result;
}
Sample Solution:
int S(int n)
{
   int result;
   result = 0;
   while (n >= 1) {
      result += n*n;
      n--;
   }
   return result;
}

  CSCI 160 Exam Quick Reference Sheet: Sections F15N01-F15N04
Comments:    Single line //       or Multi-line  /* ....
                                                    .... */
C++ operators
=============
Arithmetic operators:     +   -   *   /   %   ++  --
Assignment operators:  =  +=  -=  *=  /=  %=
Boolean operators:     &&  ||  !  ==  !=  <=  >=  <  >

Data Types
=======================================================
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 declarations (with/without initialization)
==========================================================
int    i;       int    i = 3;
char   c;       char c = 'Q';   char c = '\n';
bool   b;       bool b = true;
long arr[5];    long arr[5] = { 0, 0, 0, 0, 0 };   // array assignment only valid
char str[10];   char str[] = "some text";          //    at point of declaration

Sample constant declarations
============================
const double Pi = 3.1415;
const char[] ErrMsg = "Error: something terrible happened!\n";

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("%s", &a);  // read text into variable a (char[])
scanf("%*s");     // read and discard the next word of input
scanf("%[abc]", &x); // read an a, b, or c into variable x
scanf("%*[ \t\n]%c", &x); // skip tabs, spaces, and newlines and read next char into x
scanf("%4d", &i); // read a maxium of 4 digits into int variable i
fgets(arr, 100, stdin); // read the rest of the line (up to 100 chars max) into the char array
x = getc(stdin);  // read a single character into char variable x
ungetc(c, stdin); // take char c and push it into the input buffer

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 
  // (%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", a);  // print the contents of character array a

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         double sqrt(double)
char toupper(char)     LONG_MIN, LONG_MAX

cstring                              cstdlib
-------                              -------
char[] strcat(char[],  char[])       int abs(int)
char[] strncat(char[], char[], int)  int atoi(char[])
char[] strcpy(char[],  char[])       float atof(char[])
char[] strncpy(char[], char[], int)  void srand(time(NULL)) // needs ctime lib 
int    strcmp(char[],  char[])       int rand(int)
int    strncmp(char[,] char[], int)
int    strlen(char[]

Sample control structures
=========================
if (expr) {                  // works on short, int, long,      for (x = 1; x < 9; x++) {
   .......                   //    char, or enum values             ....
} else if (expr) {           switch (expr) {                    }
   ........                     case value1:
} else {                            .....                       while (x < 9) {
   ........                         break;                          ....
}                               case value2:                        x++;
                                    .....                       }
// is X between 3 and 9?            break;
if ((3 < X) && (X < 9)) {       default:                        do {
   // yes it is                     .....                           ....
} else {                            break;                          x++;
   // no it isn't            };                                 } while (x < 9);
}
         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;                   }                                  int array[20];
}                                                                  initArray(array, 20);
                                                                }
void initArray(int arr[], int size)
{
   for (int i = 0; i < size; i++
       arr[i] = 0;
}