Tutorial 5

This tutorial begins to address the concept of built-in functions in C++. While the student has begun to utilize some built-in functions, for example the *getline* function from tutorial 3, this tutorial moves beyond those functions closely tied to a basic data type. The author begins with the introduction of some of the basic mathematical functions. Once these have been covered, functions to generate random number and format numeric output are introduced. The tutorial concludes by sending program output to a data file.

After completing the tutorial, the student will be able to:

- Use built-in mathematical functions
- Generate random numbers
- Format the numeric output in a C++ program
- Send program output to a file in a C++ program

Introduction to functions

As you learned in tutorial 3, a function is a block of code that performs a specific task. Functions serve three main purposes:

- Make problem solving easier by allowing programmers to break large and complex problems into small and manageable tasks
- Speed up program writing by allowing programmers to use existing code to perform common tasks
- The programmer does not have to duplicate the code in different parts of the program because functions can be used as many times as necessary

Some functions, such as the *getline* function, require you to enter information between a set of parentheses following the function name. The information can be one or more variables, named constants, literal constants, or keywords. Each item of information within a function’s parentheses is called an actual argument. Each actual argument represents information that the function needs in order to perform its task. Note however that not all functions require actual arguments. For example, the main function does not require any actual arguments.

Programmers can include two different types of functions in a program: program-defined and built-in functions. A program-defined function is a function whose task is determined by the programmer and defined within the program in which the function is used. Program-defined functions will be covered is a later tutorial. A built-in function, on the other hand, is a function whose task is predefined, and whose code is contained in a library file that comes with the language compiler and resides on your computer’s hard disk. To use a built-in function in a program, you must call, or invoke, it by including its name and actual arguments (if any are required) in a statement. You must also include the appropriate library file in the program.

Built-in functions can be value-returning functions or void functions. A value-returning function returns a value after completing its assigned task. A void function, on the other hand, does not return a value. Both value-returning and void function will be covered in great detail in later tutorials.

Built-in mathematical functions

Most programming languages include a set of built-in functions for performing common mathematical tasks. In C++ these functions are defined in the *cmath* library file. Therefore you will need to include the *#include <cmath>* directive in any program that uses these functions. The functions covered in this tutorial are only a part of the functions contained in the *cmath* library. The first two functions covered are *pow* and *sqrt*, and are considered to be exponential functions. The syntax of how they are called along with what they return are listed below.

- pow(base, exponent) - returns the value of
*base*raised to the power of the value*exponent*(this is written in some languages as base ^ exponent) - -
*base*and*exponent*can be values in the float range - - the
*pow*function returns a result that is of the double type - sqrt(number) - returns the square root of the value
*number* - -the
*sqrt*function returns a result that is of the double type

The remaining three mathematical functions covered are trigonometric functions. These functions are used to calculate the cosine, sine, and tangent of x, where x is an angle expressed in radians. Because angles are typically expressed in degrees, you will usually need to convert the degrees to radians before using these functions. You convert degrees to radians using the equation: radians = degrees * pi / 180 (where pi is represented as 3.141593). The syntax of how these functions are called along with what they return are listed below.

- cos(x) - returns the cosine of the angle
*x*, where*x*is represented in radians - sin(x) - returns the sine of the angle
*x*, where*x*is represented in radians - tan(x) - returns the tangent of the angle
*x*, where*x*is represented in radians

* all three trigonometric functions return a result that is of the double type

Note that since both exponential functions and all three trigonometric functions return results that are of the double type, their result may need to be type cast dependent upon how the results are to be used within the program.

Generating random numbers

The built-in function used to generate random numbers is referred to as the random number generator. The *rand* function, which is defined in the *cstdlib* library file, is the random number generator in C++. The *rand* function, when invoked, will produce a random number (integer) that is greater than or equal to zero, but less than or equal to the value of RAND_MAX (a symbolic constant defined in the *cstdlib* library file, usually having a value of 32,767). The syntax for calling the random number generator is as follows:
*rand()*

In some programming languages you must initialize (or seed) the random number generator, otherwise the same series of numbers will be generated each time the program is executed. In C++, the *srand* function is used to initialize the random number generator. The statement for doing this is as follows:
*srand(time(NULL));*

Similar to the *rand* function, the *srand* function is defined in the *cstdlib* library file, however the *time* function is defined in the *ctime* library file. The *time* function returns the number of seconds that have elapsed since midnight of January 1, 1970. Therefore, every time the program is executed, a different value will result and seed the random number generator. NULL is a symbolic constant that is defined both in the *cstdlib* and *ctime* libraries.

The most popular way of incorporating the random number generator into a program is to utilize it in producing a set of integers within a given range. Since the random number generator produces a value (integer) greater than or equal to zero, but less than RAND_MAX, the random number generator must be incorporated into another formula to produce a number within a desired range. The formula below can be used to generate a random number between the ranges of *lowerbound* and *upperbound*.

lowerbound + rand() % (upperbound – lowerbound + 1)

Formatting numeric output

In a C++ program numeric output that contains a decimal point is displayed in either a fixed-point or exponential notation format, and the notation used is determined by the size of the number to be displayed. For example, smaller numbers (numbers with six or fewer digits to the left of the decimal point) will be displayed in fixed-point notation, while larger numbers will be displayed in exponential notation.

C++ has a fixed stream manipulator that makes output be displayed in fixed-point notation only for small and large numbers alike. In order to use the fixed stream manipulator to display numbers on the screen, you would use the following statement: *cout << fixed;*. After the issuance of this statement, all numeric output would be in a fixed-point notational format. However, the fixed stream manipulator needs to be coupled with another function that will properly set the precision (number of decimal places) to be used in displaying the fixed output.

The *precision* function is used in conjunction with the fixed stream manipulator to display fixed-point notation. The *precision* function uses the following syntax to specify how many places after the decimal to display in each number: *precision(numberOfDecimalPlaces)*. For example, the statement *cout.precision(2);* would be used to display numeric output with two places to the right of the decimal on the screen. The *precision *function is defined in the *iostream* library file.

Note that if you wish for all output going to the screen to be of a fixed format, then the fixed stream manipulator and *precision* function must appear before the first cout statement that display a number. Both settings will remain in effect until the program encounters another statement that changes the setting. The program on page 177 of the text shows an example of using these statements.

Sending output to a file

The steps for creating an output file and writing data to it are as follows:

- Enter the
*#include <fstream>*directive in the program - Create an object that represents the output file in the program
- Open (or create) the output file and associate it with the output file object created previously
- Write the program’s output to the output file
- Close the output file

By including the *#include <fstream>* directive in the program, you will be allowed to create an ofstream object that represents an output file. The following statement will create an ofstream object called *outFile*: *ofstream outFile;*. Once the ofstream object is defined, you must open the output file and associate it with the output file object (*outFile*) just created. This is accomplished through the following statement: *outFile.open("filename");* , where *filename* is the actual name of the file on the system you are using.

You have been using the following format to write data to the screen: *object << data;*. It just so happens that up until now the only object that you have been using has been the *cout* object (remember the *cout* object represents the screen). Now we will replace the *cout* object with the *outFile* object, and our output will be sent to a file instead of being sent to the screen. For example, to send the message "Hello" to the screen you would use the following statement: *cout << "Hello" <<endl;*. However to the send the same message to the output file we have opened, we would use the following statement: *outFile << "Hello" << endl;*. The final statement to properly close the output file that we have created and written data to is as follows:
*outFile.close();*

Note that when you open the output file, unless otherwise specified the file will be opened in output mode. To open the file in another mode the following format must be used: *outFile.open("filename", ios:mode);*, where *mode* is the file mode to use. The two file modes that will be discussed at this time will be *out* and *app*. By using *out*, the file will be opened in output mode. When using the output mode the computer creates a new, empty file. If a file by the particular *filename* being used exists, the existing file will be erased and a new file will begin. Make sure of what you are doing when using the output mode. By using *app*, the file will be opened in append mode. Append mode will not erase a file if it exists, but instead will append data to the already existing file.

- If you have a calculator that performs basic trigonometric functions, perform basic tasks and then do the same in a simple C++ program. While many students have performed these functions with a calculator, most have not on a computer. This will enable them to make the connection, and see the computer as a true tool.
- Take a program where the output of numeric data was not previously formatted, and format it using various decimal places. You may also experiment with showing and not showing decimal places.
- Code a program that prints out the same number using different formats. You will have to code different manipulators at strategic points in the program in order to accomplish this task. This will allow you to see first-hand how manipulators stay in effect until another one is encountered.

1. a actual arguments 5. a cout << sin(55 * 3.141593 / 180);

2. c #include <cmath> 6. a rand

3. c pow(5,3) 7. b 3 + rand() % (9 – 3 + 1)

4. d sqrt(100) 8. c srand(time(NULL));

- total = pow(num1, 2) + pow(num2, 2);
- cout << sqrt(number);
- cout << sqrt(pow(num1, 2) + pow(num2, 2));
- answer = pow(x, 2) * pow(y, 3);
- rate = pow(future / present, 1 – term) - 1;
- cout << tan(25 * 3.141593 / 180);
- cout << cos(.9);
- cout << 50 + rand() % (100 – 50 + 1);
- cout << abs(difference);
- cout << log(100) << " " << log10(100);
- In this exercise, the student completes a program that displays the value of RAND_MAX. Answers may vary.

//T5ConE11.cpp - displays your system's RAND_MAX value #include <iostream> #include <cstdlib> using namespace std; int main() { cout << "The value of RAND_MAX on my system is: " << RAND_MAX << endl; return 0; } //end of main function |

12. Changes made to the original code are shaded.

//T5ConE12.cpp - displays a random number between 200 and 500 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { //display output srand(time(NULL)); cout << 200 + rand() % (500 - 200 + 1) << endl; return 0; } //end of main function |

13. The original program displays the same three random numbers because it does not contain the srand

function, which initializes the random number generator. Changes made to the original code are shaded.

//T5ConE13.cpp - displays three random numbers #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { //display output srand(time(NULL)); cout << 1 + rand() % (10 - 1 + 1) << endl; cout << 1 + rand() % (10 - 1 + 1) << endl; cout << 1 + rand() % (10 - 1 + 1) << endl; return 0; } //end of main function |

Solutions to Application Lesson Exercises

1. The program should display 12396 as the principal assuming a monthly payment of $400,

a three-year loan, and a 10% annual interest rate.

//T5AppE01.cpp - displays the present value of a series of periodic payments #include <iostream> #include <cmath> #include <fstream> using namespace std; int main() { int payment = 0; int term = 0; float rate = 0.0; float principal = 0.0; ofstream outFile; outFile.open("T5AppE01.dat"); //enter input items cout << "Enter the desired monthly payment: "; cin >> payment; cout << "Enter the term (in years): "; cin >> term; term = term * 12; cout << "Enter the annual interest rate: "; cin >> rate; rate = rate / 12; //calculate present value (principal) principal = payment * (1 - pow(rate + 1, -term)) / rate;
//display output items cout << fixed; cout.precision(0); cout << "You can borrow up to $" << principal << endl; outFile << fixed; outFile.precision(0); outFile << "You can borrow up to $" << principal << endl; outFile.close();
return 0; } //end of main function |

Contents of the T5AppE01.dat file

You can borrow up to $12396 |

2. The program should display 65904 as the future value assuming an annual payment of $5000

for 10 years at a 6% interest rate.

//T5AppE02.cpp - displays the future value of a series of periodic payments #include <iostream> #include <cmath> #include <fstream> using namespace std; int main() { int payment = 0; int term = 0; float rate = 0.0; float futureVal = 0.0; ofstream outFile; outFile.open("T5AppE02.dat"); //enter input items cout << "Enter the periodic payment: "; cin >> payment; cout << "Enter the term (in years): "; cin >> term; cout << "Enter the annual interest rate: "; cin >> rate;
//calculate future value futureVal = (payment * (pow(1 + rate, term) - 1)) / rate; //display output items cout << fixed; cout.precision(0); cout << "Future value: " << futureVal << endl; outFile << fixed; outFile.precision(0); outFile << "Future value: " << futureVal << endl; outFile.close();
return 0; } //end of main function |

Contents of the T5AppE02.dat file

Future value: 65904 |

3. The program should display 965.55 as the monthly payment assuming a $120000 mortgage

for 30 years at a 9% interest rate.

//T5AppE03.cpp - displays the monthly payment for a mortgage #include <iostream> #include <cmath> #include <fstream> using namespace std; int main() { int principal = 0; int term = 0; float rate = 0.0; float payment = 0.0; ofstream outFile; outFile.open("T5AppE03.dat"); //enter input items cout << "Enter the principal: "; cin >> principal; cout << "Enter the term (in years): "; cin >> term; term = term * 12; cout << "Enter the annual interest rate: "; cin >> rate; rate = rate / 12; //calculate monthly payment payment = principal * (rate / (1 - pow(rate + 1, -term))); //display output items cout << fixed; cout.precision(2); cout << "Monthly payment: " << payment << endl; outFile << fixed; outFile.precision(2); outFile << "Principal: " << principal << endl; outFile << "Term (years): " << term / 12 << endl; outFile << "Rate (annual): " << rate * 12 << endl; outFile << "Monthly payment: " << payment << endl; outFile.close(); return 0; } //end of main function |

The contents of the T5AppE03.dat file

Principal: 120000 Term (years): 30 Rate (annual): 0.09 Monthly payment: 965.55 |

4.

//T5AppE04.cpp - displays the sine, cosine, and tangent of an angle #include <iostream> #include <cmath> using namespace std; int main() { const float PI = float(3.141593); int angle = 0; float angleSine = 0.0; float angleCosine = 0.0; float angleTangent = 0.0;
//enter input item cout << "Enter the angle (in degrees): "; cin >> angle;
//calculate sine, cosine, and tangent angleSine = sin(angle * PI / 180); angleCosine = cos(angle * PI / 180); angleTangent = tan(angle * PI / 180);
//display output items cout << fixed; cout.precision(2); cout << "Sine: " << angleSine << endl; cout << "Cosine: " << angleCosine << endl; cout << "Tangent: " << angleTangent << endl; return 0; } //end of main function |

5.

//T5AppE05.cpp - displays random numbers #include <iostream> #include <ctime> #include <cstdlib> #include <fstream> using namespace std; int main() { //declare variables int num1 = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = 0; int num6 = 0; ofstream outFile; outFile.open("T5AppE05.dat", ios::app); //generate random numbers srand(time(NULL)); num1 = 1 + rand() % (54 - 1 + 1); num2 = 1 + rand() % (54 - 1 + 1); num3 = 1 + rand() % (54 - 1 + 1); num4 = 1 + rand() % (54 - 1 + 1); num5 = 1 + rand() % (54 - 1 + 1); num6 = 1 + rand() % (54 - 1 + 1); //display output items cout << num1 << endl; cout << num2 << endl; cout << num3 << endl; cout << num4 << endl; cout << num5 << endl; cout << num6 << endl; outFile << num1 << endl; outFile << num2 << endl; outFile << num3 << endl; outFile << num4 << endl; outFile << num5 << endl; outFile << num6 << endl; outFile.close(); return 0; } //end of main function |

Contents of the T5AppE05.dat file may vary.

50 46 34 6 51 35 5 10 50 6 41 44 |

6. The total payment is 17280. The total interest is 1951.

//T5AppE06.cpp - displays the present value of a series of periodic payments //also displays the total amount paid and the total interest paid #include <iostream> #include <cmath> #include <fstream> using namespace std; int main() { const int PAYMENT = 360; const int TERM = 48; float rate = 0.0; float principal = 0.0; float totPaid = 0.0; float totInterest = 0.0; ofstream outFile; outFile.open("T5AppE06.dat"); //enter input items cout << "Enter the annual interest rate: "; cin >> rate; rate = rate / 12; //calculate present value (principal) principal = PAYMENT * (1 - pow(rate + 1, -TERM)) / rate; //calculate total amount paid and total interest paid totPaid = PAYMENT * TERM; totInterest = totPaid - principal; //display output items cout << fixed; cout.precision(0); cout << "You can borrow up to $" << principal << endl; cout << "Total paid $" << totPaid << endl; cout << "Total interest $" << totInterest << endl; outFile << fixed; outFile.precision(0); outFile << "You can borrow up to $" << principal << endl; outFile << "Total paid $" << totPaid << endl; outFile << "Total interest $" << totInterest << endl; outFile.close();
return 0; } //end of main function |

Contents of the T5AppE06.dat file

You can borrow up to $15329 Total paid $17280 Total interest $1951 |

7. The present value of the annuity is 425678. The better option is the lump sum payment of 450000.

//T5AppE07.cpp - displays the present value of an annuity #include <iostream> #include <cmath> using namespace std; int main() { int payment = 50000; int term = 20; float rate = float(.1); float presentVal = 0.0;
//calculate present value presentVal = payment * (1 - pow(rate + 1, -term)) / rate;
//display output items cout << "Present value of annuity " << presentVal << endl;
return 0; } //end of main function |

8. The number of years required to double an investment using a 6% interest rate is 11.9.

//T5AppE08.cpp - displays the number of years its takes to double an investment #include <iostream> #include <cmath> using namespace std; int main() { //declare variables float years = 0.0; float rate = 0.0;
//enter interest rate cout << "Enter the annual interest rate: "; cin >> rate; //calculate years years = log(2) / log(1 + rate);
//display output items cout << fixed; cout.precision(1); cout << "Years required to double an investment: " << years << endl;
return 0; } //end of main function |

9. Changes made to the original code are shaded.

//T5AppE09.cpp - displays the square and square root of a number #include <iostream> #include <cmath> using namespace std; int main() { //declare and initialize variables float number = 0.0; float square = 0.0; float sqRoot = 0.0; //enter input item cout << "Enter a number: "; cin >> number; //calculate square and square root square = pow(number, 2); sqRoot = sqrt(number); //display output items cout << "Square: " << square << endl; cout << "Square Root: " << sqRoot << endl; return 0; } //end of main function |