Answers to In-class Exercises in Lectures 9, 10, 11 1 Lecture 9 Exercises The only exercises we did in Lecture 9 involved library functions. The answers are provided here for your information but there will not be any questions on the quiz that require knowledge of library functions. 1.1 Exercise 1 Replace bold lines in following program with the abort library function. #include <fstream> // provides ifstream, ofstream #include <iostream> // provides cout using namespace std; int main() { ifstream infile; infile.open("yards.in"); if (!infile) { cout << "Unable to open input file" << endl; cout << "Abnormal termination program" << endl; return 0; } return 0; } 1.1.1 Exercise 1 Answer #include <fstream> // provides ifstream, ofstream #include <iostream> // provides cout #include <cstdlib> // provides abort using namespace std; int main() { ifstream infile; infile.open("yards.in"); if (!infile) { cout << "Unable to open input file" << endl; abort( ); } return 0; } 1.2 Exercise 2 Write a code segment to generate and display 5 random numbers between 0 and 1000. assume srand has already been called with the current time to properly initialize the random generator 1.2.1 Exercise 2 Answer int randomNumber ; for (int i = 1 ; i <= 5 ; i++) { randomNumber = (float) rand ( ) /RAND_MAX * 1000; cout << randomNumber << endl; } 2 Lecture 10 Exercises 2.1 Exercise 1 1) write a function which accepts an integer value as input, and returns an integer which is the cube of that input. y Cube int y 3 int 2.1.1 Exercise 1 answer int Cube (int y) { return y * y * y ; } 2.2 Exercise 2 Write a function that accepts a char as input and returns true if the char is a digit from 0 to 9 or false if the character is not a digit from 0 to 9. ch char IsDigit 2.2.1 Exercise 2 Answer bool IsDigit (char ch) { if ((ch >= ‘0’) && (ch <= ‘9’)) return true; else return false; } bool true if ch is 0 to 9 false if ch is not 0 to 9 2.3 Exercise 3 Write a main function that calls the Cube function from exercise 1. Have it calculate the cube of the numbers from 1 to 10 and display them. int Cube (int y) 2.3.1 Exercise 3 Answer int Cube (int y); //function prototype int main () { for (int i = 1; i <= 10; i++) { cout << i << “ cubed is” << Cube (y) << endl; } return 0; } 2.4 Exercise 4 Write a main function that calls the IsDigit function from Exercise 2. Have it read in 10 input characters from a user and for each one, display whether it is a digit or not. bool IsDigit (char ch); // function prototype 2.4.1 Exercise 4 Answer bool IsDigit (char ch); // function prototype int main ( ) { char inputChar; for (int i = 1; i <= 10; i++) { cout << “Enter character: “; cin >> inputChar; if (IsDigit (inputChar)) cout << inputChar << “ is a digit” << endl; else cout << inputChar << “ is not a digit” << endl; } return 0; } 2.5 Exercise 5 Write a function named Smallest that takes three integer inputs and returns an integer that is the smallest of the three inputs. Write the prototype for the Smallest function. Write a program that gets 3 integers from a user and displays the smallest. 2.5.1 Exercise 5 Answer #include <iostream> using namespace std; int Smallest (int a, int b, int c); // function prototype int main () { int x, y, z; cout << “Enter three integers ”; cin >> x >> y >> z; cout << “The smallest integer is: ” << Smallest (x, y, z) << endl; return 0; } int Smallest (int a, int b, int c) { int smallest = a; if (smallest > b) smallest = b; if (smallest > c) smallest = c; return smallest; } 2.6 Exercise 6 Write a function that, given a letter of the alphabet, returns true if the letter is a vowel (lower or uppercase) and returns false if the letter is not a vowel. letter (char) IsAVowel true if letter is a vowel false if letter is not a vowel Also write the prototype for IsAVowel. Write a program to invoke the IsAVowel function. Inputs a letter and prints out whether it is or is not a vowel. 2.6.1 Exercise 6 Answer #include <iostream> using namespace std; bool IsAVowel (char); //function prototype int main ( ) { char ch; cout << “Enter a letter: “ ; cin >> ch ; if (IsAVowel (ch)) cout << ch << “ is a vowel “ << endl; else cout << ch << “ is not a vowel “ << endl; return 0; } bool IsAVowel (char ch) { switch (ch) { case ‘a’: case ‘A’: case ‘e’: case ‘E’: case ‘i’: case ‘I’: case ‘o’: case ‘O’: case ‘u’: case ‘U’: return true; } return false; } 2.7 Exercise 7 1) Find the error in each of the following program segments and explain how to fix it. a) int sum (int x, int y) { int result; result = x + y; } b) int sum (int n) { if (0 == n) return 0; else n = n + n; } c) in main program: double x = 1E10; cout << "square of 1E10 = " << square (x) << endl; int square (int x) return x * x; } { 2.7.1 Exercise 7 Answer 1a) result is a local variable. Calling function cannot use the result because it was never returned. Add return statement. int sum (int x, int y) { int result; result = x + y; return result; } b) n is local parameter. The calling function’s parameter never changed. Add return statement int sum (int n) { if (0 == n) return 0; else n = n + n; return n; } c) in main program, x is data type double. It will be truncated when the square function is invoked and incorrect values will be produced. Promotion rules were not followed. Cannot safely convert double to integer. Fix by changing argument and return value for Square function to data type double . double x = 1E10; cout << "square of 1E10 = " << square (x) << endl; double square (double x) return x * x; } { 2.8 Exercise 8 Find the error in the following function and fix it. void displayErrorMessage (int errorNumber) { switch (errorNumber) { case 0: cout << "Fatal Error!" << endl; break; case 1: cout << "Error!" << endl; break; default: cout << "Invalid error code" << endl; } return true; } 2.8.1 Exercise 8 Answer This function is defined with a void return value but we are returning a boolean constant. Fix by replacing the return true; statement with a return; statement. Find the error in the following function and fix it. void displayErrorMessage (int errorNumber) { switch (errorNumber) { case 0: cout << "Fatal Error!" << endl; break; case 1: cout << "Error!" << endl; break; default: cout << "Invalid error code" << endl; } return; } 3 Lecture 11 Exercises Change the GetMinAndMax function (see below) so that it validates the user’s input. Only integers between 0 and 1000 are allowed (including 0 and 1000). If invalid input is detected, GetMinAndMax stops processing input and returns false to the caller. If GetMinAndMax successfully processes the input and calculates the minimum and maximum values, it returns true to the caller. int main() { int minimum = 0, maximum = 0; GetMinAndMax (minimum, maximum); cout << "Minimum value is " << minimum << endl; cout << "Maximum value is " << maximum << endl; return 0; } void GetMinAndMax (int &min, int &max) { int input; min = INT_MAX; max = INT_MIN; for (int i = 0; i <= 5; i++) { cout << “Enter an integer: “; cin >> input; if (min > input) min = input; if (max < input) max = input; } } 3.1.1 Exercise 1 Answer Change return type of GetMinAndMax to bool and add an if statement to validate the input right after the cin statement. int main() { int minimum = 0, maximum = 0; GetMinAndMax (minimum, maximum); cout << "Minimum value is " << minimum << endl; cout << "Maximum value is " << maximum << endl; return 0; } bool GetMinAndMax (int &min, int &max) { int input; min = INT_MAX; max = INT_MIN; for (int i = 0; i <= 5; i++) { cout << “Enter an integer: “; cin >> input; if ((input < 0) || (input > 1000)) return false; if (min > input) min = input; if (max < input) max = input; } } 3.2 Exercise 2 1) Change the main function so that it calls your new version of GetMinAndMax properly 3.2.1 Exercise 2 Answer Must check the bool return value before using the minimum and maximum values returned. If the return value is false, these values are meaningless. Add an if statement to the call to GetMinAndMax to make sure the values are meaningful before you display them to the user. bool GetMinAndMax (int &min, int &max); //function prototype int main () { int minimum = 0, int maximum = 0; if ((GetMinAndMax (minimum, maximum)) { cout << “Minimum value is “ << minimum << endl; cout << “Maximum value is” << maximum << endl; } } 3.3 Exercise 3 Fix the error in the following program segment void sum (int n) { if (0 == n) return 0; else n = n + n; } 3.3.1 Exercise 3 Answer n is a local variable. No information was passed back to the caller. Change n to a reference parameter by adding &. void sum (int & n) { if (0 == n) return 0; else n = n + n; } 3.4 Exercise 4 3) Rewrite the following function prototype to return the result as a parameter instead of as a return value int Square (int y); 3.4.1 Exercise 4 Answer Add a reference parameter called result and use that to pass the information back to the calling function. Also change return type to void since nothing will be returned using the return statement. void Square (int y, int &result ); Exercise 5 Produce the documentation header for the GetMinAndMax function 3.4.2 Exercise 5 Answer /* * GetMinAndMax – Reads in 5 integers from the user and returns the smallest and * largest value to the caller. * * Pre: Input parameters - none * Output parameters – int & min Will hold the smallest value when function returns * int & max will hold the largest value when the function returns * * Post: Return value – if true min contains the smallest value inputted from the user and * max contains the largest value. * if false min and max may not contain valid data * */ 3.5 Exercise 6 Write a C++ function that satisfies the following pre and post conditions: /* * IsUppercase * * PRE: Input character ch. Function will determine if this * is an uppercase letter or not. * POST: Return value true if input character ch is an upper * * * */ case letter in the range A - Z. false if input character ch is not an upper case letter in the range A - Z. 3.5.1 Exercise 6 Answer bool IsUppercase (char ch) { if ((ch >= ‘A’ ) && (ch <= ‘Z’)) return true; else return false; }