A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses: int main(void). Ideally, your main( ) function should be very short and should consist primarily of function calls Built-in functions Build-in functions are part of the compiler package, such as exit(1);
A function definition consists of two parts: interface and body. The interface of a function (also called its prototype) specifies how it may be used. It consists of three entities: The function name. This is simply a unique identifier. The function parameters (also called its signature). This is a set of zero or more typed identifiers used for passing values to and from the function. The function return type. This specifies the type of value the function returns. A function which returns nothing should have the return type void.
The body of a function contains the computational steps (statements) that comprise the function. Using a function involves ‘calling’ it. A function call consists of the function name followed by the call operator brackets ‘()’, inside which zero or more comma-separated arguments appear
int Power (int base, unsigned int exponent) { intresult = 1; for (int i = 0; i < exponent; ++i) result *= base; return result; } Function body Note: A function should be declared before its is used
User-defined functions User-defined functions are created by you, the programmer.
Declare the function. The declaration, called the function prototype, tells the computer the name, return type, and parameters of the function. This statement is placed after #include (and other headers) and before int main(void).
FORMAT NOTE: Please have all of your functions end with return.
2. Define the function. The function definition tells the compiler what task the function will be performing. A function definition cannot be called unless the function is declared. The function prototype and the function definition must agree EXACTLY on the return type, the name, and the parameters. The only difference between the function prototype and the function header is a semicolon (see diagram below). The function definition is placed AFTER the end of the int main(void) function. The function definition consists of the function header and its body. The header is EXACTLY like the function prototype, EXCEPT that it contains NO terminating semicolon
Local Variable..a variable that is restricted to use within a function of a program. Our first style of function will simply perform an independent task. It will not send or receive any parameters and it will not return any values. The word void appears as the return type and the parameters.
#include int Power (int base, unsigned int exponent ); // function declaration main (void) { cout << "2 ^ 8 = " << Power(2,8) << '\n'; } int Power (int base, unsigned int exponent) { intresult = 1; for (int i = 0; i < exponent; ++i) result *= base; return result; }
C++ supports two styles of parameters: value and reference. A value parameter receives a copy of the value of the argument passed to it A reference parameter, on the other hand, receives the argument passed to it and works on it directly
#include void Foo (int num) { num = 0; cout << "num = " << num << '\n'; } int main (void) { int x = 10; Foo(x); cout << "x = " << x << '\n'; return 0; }
variables generally denote memory locations where variable values are stored The storage class specifier register may be used to indicate to the compiler that the variable should be stored in a register if possible. For example: for (register int i = 0; i < n; ++i) sum += i;
An enumeration of symbolic constants is introduced by an enum declaration. This is useful for declaring a set of closely-related constants. For example, enum {north, south, east, west}; introduces four enumerators which have integral values starting from 0 (i.e., north is 0, south is 1, etc.) enum {north = 10, south, east = 0, west}; Here, south is 11 and west is 1.
However, instead of replicating this expression in many places in the program, it is better to define it as a function: int Abs (int n) { return n > 0 ? n : -n; }
//Screen display shown at the right //Prototyping, defining and calling a function #include #include void astericks(void); //function prototype int main(void) { system("CLS"); cout<<"Heads up, function!\n"; astericks( ); //function call cout<<"Again, function!\n"; astericks( ); //function call cout<<"Job well done!\n"; return 0; //main( ) is over - ALL STOP!! } //function definition void astericks(void) { int count; // declaring LOCAL variable for(count = 1; count<=10; count++) cout<<"*"; cout<<endl; return; //return value is VOID, no return } SCREEN DISPLAY Heads up, function! ********** Again, function! ********** Job well done!
Our second style of function will take arguments (parameters) but will not return a value. The argument list in the parentheses specifies the types and number of arguments that are passed to the function. void sum(int x, int y, int z); //function prototype Acceptable Prototypes voi d add(int x, int y); void add(int, int); While both of these prototypes are acceptable, we will be using the first style.
//Example program //Screen display shown at the right //Passing arguments to a function #include #include void greeting(int x); //function prototype int main(void) { system("CLS"); greeting(5); //function call- argument 5 int number; do { cout >number; } while ((number 10)); greeting(number); //argument is a variable return 0; } //function definition void greeting(int x) // formal argument is x { int i; // declaring LOCAL variable for(i = 0; i < x; i++) { cout<<"Hi "; } cout<<endl; return; //return value is VOID, no return } Screen Display Hi Hi Hi Hi Hi Please enter value(1-10): 4 Hi Hi Hi Hi
Our third style of function takes no arguments, but will return a value. Up until now, we have been communicating information TO a called function. Now we will be returning information FROM the function by using the function return value. The return value can be a constant, a variable, or an expression. The only requirement is that the return value be of the type specified in the function prototype. return_type functionName(void) //function header { statements; return (value); //value is of type return_type }
C++ compilers include built-in functions to make programming easier. The number and type of functions available to you depends upon the compiler you are using. These functions that come with the compiler are called "built-in" library functions.
Library functions are just like the functions that you, as the programmer, create and are used in a similar manner. The only difference is that the source code (definition) for library functions does NOT appear in your program. The prototype for the library function is provided to your program using the #include compiler directive. The most common library functions. Character classification and conversion Math functions Data conversion Time functions
Required header: #include C++ uses the American Standard Code for Information Interchange (ASCII) character set. The CTYPE library includes character classification functions. A character is passed to the functions and the functions return values that can be stored or printed.
CategoryASCII Characters Uppercase letters 'A' through 'Z' Lowercase letters 'a' through 'z' Digits (0 through 9) '0' through '9' Whitespace Space, tab, line feed(newline), and carriage return Punctuation !"#$%&'()*+,-./:; Blank spaceThe blank space character Basic ASCII Categories
1. isalnum( ) returns a TRUE (nonzero) if the argument is digit 0-9, or an alphabetic character (alphnumeric). Otherwise returns FALSE. 2. isalpha( ) returns TRUE if the argument is an upper or lower case letter. 3. isascii( ) returns TRUE if the integer argument is in the ASCII range Treats as non-ASCII. 4. isdigit( )returns TRUE if the argument is a digit isgraph( ) returns TRUE if the argument is any printable character from ASCII 32 to 127, except the space. 6. islower( )returns TRUE if the argument is a lowercase letter. 7. isupper( )returns TRUE if the argument is an uppercase leter. 8. ispunct( ) returns TRUE if the argument is any punctuation character (see chart above). 9. isspace( )returns TRUE if the argument is a whitespace (see chart above).
toascii( ) converts the argument (an arbitrary integer) to a valid ASCII character number c = toascii(500); //c gets number 116 // (modulus 500%128) c = toascii('d'); //c gets number 100 tolower( ) converts the argument (an uppercase ASCII character) to lowercase. c = tolower('Q'); // c becomes 'q' toupper( ) converts the argument (a lowercase ASCII character) to uppercase. c = toupper('q'); //c becomes 'Q' **Note: tolower( ) and toupper( ) will actually check to see if the argument is the appropriate uppercase or lowercase before making the conversion.
Required headers: #include #include Computers can be used to simulate the generation of random numbers with the use of the rand( ) function. This random generation is referred to as a pseudo- random generation. These created values are not truly "random" because a mathematical formula is used to generate the values.
rand( ) returns a random positive integer in the range from 0 to 32,767. This function can be thought of as rolling a die with 32,767 faces. The numbers are generated by a mathematical algorithm which when given a starting number (called the "seed"), always generates the same sequence of numbers. Since the same sequence is generated each time the seed remains the same, the rand( ) function generates a pseudo- random sequence. To prevent the same sequence from being generated each time, use srand(x) to change the seed value
srand(x) used to set the starting value (seed) for generating a sequence of pseudo-random integer values. The srand(x) function sets the seed of the random number generator algorithm used by the function rand( ). A seed value of 1 is the default setting yielding the same sequence of values as if srand(x) were not used. Any other value for the seed produces a different sequence.
In order to produce random integer numbers within a specified range, you need to manipulate the rand( ) function. The formula is: int number = a + rand( ) % n; a = the first number in your range n = the number of terms in your range (range computed by largest value - smallest value + 1)
Sample program: /*generate 10 random numbers between 10 and 55 inclusive, without repetition of the sequence between program runs*/ #include #include #include int main(void) { // to prevent sequence repetition between runs srand(time(NULL)); for(int i = 1; i <=10; i++) // looping to print 10 numbers { cout<< 10 + rand( ) % 46; // formula for numbers } return 0; } Example: /*random integers between 35 and 42 inclusive*/ int num =35+rand( )% 8;
Math Functions Function Prototype Purpose abs(x) int abs(int x); returns the absolute value of an integer. fabs(x) double fabs(double x); returns the absolute value of a floating point number ceil(x) double ceil(double x); rounds up to a whole number cout<<ceil(11.2); (prints 12) (not normal rounding) floor(x) double floor(double x); rounds down to a whole number cout<<floor(11.5); (prints 11) (not normal rounding) hypot(a,b) double hypot(double a, double b); calculates the hypotenuse (c) of a right triangle where a and b are the legs. pow(x,y) double pow(double x, double y); calculates x to the power of y. If x is negative, y must be an integer. If x is zero, y must be a positive integer. pow10(x) double pow10(int x); calculates 10 to the power of x. sqrt(x) double sqrt(double x); calculates the positive square root of x. (x is >=0) fmod(x,y) double fmod(double x, double y); returns floating point remainder of x/y with same sign as x. Y cannot be zero. Because the modulus operator(%) works only with integers, this function is used to find the remainder of floating point number division.
cos(x) cosine of x sin(x) sine of x tan(x) tangent of x acos(x) arc cosine x asin(x) arc sine of x atan(x) arc tangent x cosh(x) hyperbolic cosine of x sinh(x) hyperbolic sine of x tanh(x) hyperbolic tangent of x exp(x) exponential function log(x) natural logarithm log10(x) base 10 logarithm NOTE: The trigonometric functions work with angles in radians rather than degrees. All of the trigonometric functions take double arguments and have double return types.
You can exchange simple if-else code for a single operator – the conditional operator. The conditional operator is the only C++ ternary operator (working on three values). Other operators you have seen are called binary operators (working on two values). FORMAT: conditional Expression ? expression1 : expression2;
** if the conditional Expression is true, expression1 executes, otherwise if the conditional Expression is false, expression 2 executes. If both the true and false expressions assign values to the same variable, you can improve the efficiency by assigning the variable one time: (a>b) ? (c=25) : (c=45); can be written as: c = (a>b) ? 25 : 45;
if (a>b) { c=25; } else { c=45; } can be replaced with (a>b) ? (c=25) : (c=45); The question mark helps the statement read as follows: "Is a greater than b? If so, put 25 in c. Otherwise, put 45 in c."