Listing: example.cpp template <class T> T min (T a, T b) { if (a < b) { return a
ID: 3630219 • Letter: L
Question
Listing: example.cpptemplate <class T>
T min (T a, T b)
{
if (a < b) {
return a;
} else {
return b;
}
}
Keywords:
template — the following function or class is defined as a template which can be used to create a formal definition with proper types
< class T > — T is a placeholder in the function or class for the formal datatype
Anywhere that T is used, the compiler will replace T with the specified datatype, either implicitly by usage (i.e min(int, int)), or explicitly (i.e vector).
Exercises
Write template functions that perform each of the above tasks.
You need to write the following functions (using templates):
myswap(A, B) — swap the value from A to B and B to A, so that afterwards, A and B are swapped
sum(array, length) — return the sum of elements in array of size length
count(array, value, length) — return the number of elements in array of size length that are equal to value
In the following main.cpp, you will see the usage of assert — this is a function that will cause your program to fail immediately if the result in assert() is not true. This is an easy way to test the validity of your program to make sure that things work.
You will know your lab is successful when the program runs completely and displays “All tests passed!”
Note
Put your code in lab5/part1/functions.h, not in lab5/part1/main.cpp, and make sure not to compile your header file, use only the Makefile provided below as well.
Listing: main.cpp
#include <iostream>
#include <assert.h>
#include "functions.h"
using namespace std;
#define ARRLEN 6
int main(int argc, char *argv[])
{
int x, y;
double a, b;
int iarr[] = {42, 42, 42, 56, 65, 99};
float farr[] = {3.14, 3.14, 3.2, 4.5, 7.8, 0.0};
x = 6;
y = 42;
a = 3.14159;
b = 3.14160;
assert(min(x,y) == x);
assert(min(a,b) == a);
assert(count(iarr, y, ARRLEN) == 3);
assert(count(farr, 3.14f, ARRLEN) == 2);
assert(sum(iarr, ARRLEN) == 346);
assert(sum(farr, ARRLEN) == 21.78f);
// Can't use *swap* because it's part of the STL
myswap(x, y);
assert(x == 42);
assert(y == 6);
myswap(a, b);
assert(a == 3.14160);
assert(b == 3.14159);
cout << "All tests passed!" << endl;
}
Listing: Makefile
lab5: main.cpp functions.h
g++ main.cpp -o lab5
Exceptions
As you (hopefully) recall, exceptions are a part of C++ that allows us to gracefully handle any errors in our programs without the universe going sideways. This lab walks you through creating and handling exceptions in your software.
Example
Here is an example of a program that creates a special Exception class, DivideByZero, which is thrown from divide() if the divisor is zero.
Listing: divbyzero.cc
class DivideByZero
{
public:
double dividend;
DivideByZero(double x);
};
DivideByZero::DivideByZero(double x)
{
dividend = x;
}
int divide(int x, int y)
{
if(y==0)
{
throw DivideByZero(x);
}
}
int main(int argc, char *argv[])
{
try
{
divide(12, 0);
}
catch (DivideByZero divZero)
{
cerr<<"Attempted to divide " << divZero.dividend << " by zero";
}
}
Exercise 1 – Exception Handling
The function below computes sales tax owed on a certain purchase. An error situation should occur whenever the user passes a negative price or negative sales tax into the function. There are three different ways of handling the error:
“special values” as we talked about in class, such as using a negative number to represent a problem with a value that would always be positive,
Printing out error messages and terminating the program immediately (probably not the best solution)
Throwing an exception (the best solution)
double calcSalesTax(double price, double taxRate)
{
return price * taxRate;
}
Work
In your README file with your solutions, write a brief example function for each of the following ways to handle if one or both input values are incorrect:
Return a special value. What value did you choose? Why did you choose it?
Print out an error message and causes the program to immediately exit.
Throw an object of type InvalidArgumentException in the case that either one or both inputs are invalid. Assume that the class is already defined.
Exercise 2 – Exceptions
In this problem, you will practice using these concepts again, this time implementing the InvalidArgumentException class. Supply code for the computeAge() function below such that an exception of type InvalidArgumentException is thrown whenever either of the two inputs is negative or if the current year is less than the date of birth.
int computeAge(int currentYear, int birthDate)
{
return currentYear – birthDate;
}
Work
In a file, lab5/part2/exercise2.cpp, perform the following tasks:
Implement a main function, in which you have a try statement. In this try statement, call the computeAge() function with invalid inputs. A catch statement should catch the exception, print out an error message, and cause the program to immediately exit.
Define and implement the InvalidArgumentException class such that it stores a single text error message initialized by the class’s constructor.
Exercise 3 – Inheritance
In C++, you can use inheritance to create families of exceptions, just the same way you could create families of other objects. These objects would all be related. For instance, you could create an exception class, MathException that would be the parent class for all math-related exceptions that are in your program. This way, you could treat all the math-related bugs the same way in your catch statements, or you could treat them individually with more specific catch blocks. Here is an example:
Listing: exceptions.cpp
class Base
{
public:
Base() {}
};
class Derived: public Base
{
public:
Derived() {}
};
int main()
{
try
{
throw Derived();
}
catch (Base &cBase)
{
cerr << "caught Base";
}
catch (Derived &cDerived)
{
cerr << "caught Derived";
}
return 0;
}
Try compiling and running this code and note what the output is. How could you change it so that the output was from the the other catch statement?
Work
Write a program, lab5/part2/exercise3.cpp, and perform the following tasks:
Modify the first exception class example (DivideByZero), and create a parent exception class, MathException.
From MathException, create several new exception types:
NumberTooLargeException
OutOfRangeException
ImaginaryNumberException
Write the following functions:
float multiply(float x, float y) — Multiplies x * y and if the result is greater than 2billion, throws a NumberTooLargeException, or if either parameter is larger than 5,000 throws an OutOfRangeException
float root(float x, float y) — Takes x and gets the y-root of it (i.e 4, 2 would be the square root of 4). Throws an ImaginaryNumberException object if the result would be an imaginary number
Write a main main(…) function that performs the following:
Prompts the user to input two numbers to be multiplied together
Uses those two values for the multiply() function, and depending on the result, either:
Displays the result, or
Provides the user with a useful error message and a chance to re-enter the values
Prompts the user again for two numbers to take the root
Uses those numbers for your root() function, and then either:
Displays the result, or
Provides the user with a useful error message and a chance to re-enter the values
Prompts the user to re-run the exercise, if the user enters “Y”, start at #1 again, anything else exits the program
Files
When finished, you should have:
lab5
part1
main.cpp
functions.h
Makefile
part2
README with your answers to Exercise #1
exercise2.cpp
exercise3.cpp
Makefile
Explanation / Answer
myswap(A, B) — swap the value from A to B and B to A, so that afterwards, A and B are swapped
template <class T>
T min (T& a, T& b)
{
int temp =a;
a = b;
b = temp;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.