Prewritten Functions
C++ doesn’t offer many built in keywords or functions, and that’s alright because with many compilers comes standard header files. These header files contain functions that we can use to enhance our programs and not write new functions. To call a function we either use an output statement or store it in a variable. We put the function name and then enter parenthases and put in the required parameters. A parameter is what is being passed down to the function. Assuming we already initialized the variables and have the proper heading file, to call the pow function and put into a variable x would be:
x=pow(2.0, 9) |
The pow will take the 2.0 and put it to the 9th power. Below is a table which lists some useful functions, the type of parameters, and which header file they’re in.
Function | Header File | Purpose | Parameter(s) Type | Result |
abs(x) | cmath | Returns the absolute value | int (some compilers like .NET 2005 will allow other numerical data) | int (unless other numerical data was accepted) |
sin(x) | cmath | Returns the sine | double | double |
cos(x) | cmath | Returns the cosine | double | double |
tan(x) | cmath | Returns the tangent | double | double |
pow(x, y) | cmath | Returns x to the yth power | double | double |
sqrt(x) | cmath | Returns square root of x | float | float |
toupper(x) | cctype | Returns the uppercase of a char | char | char |
tolower(x) | cctype | Returns the lowercase of a char | char | char |
clock() | ctime | Returns CPU time taken for the program to run | double | |
strcmp(x, y) | string | Returns int < 0 when y is < x, 0 when x and y are equal and int > 0 when x > y | string, string | int |
char(x) | Returns a character | int | char | |
double(x) | Returns a double | int | double | |
rand() | Returns a random number | double |
There are many more prewritten functions that come with the compilers, and many more that you can download from the web. I have just listed what I feel are the most useful prewritten functions. In the next section you’ll learn how to write your own.