Presentation is loading. Please wait.

Presentation is loading. Please wait.

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:

Similar presentations


Presentation on theme: "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:"— Presentation transcript:

1 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);

2 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.

3 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

4 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

5 User-defined functions User-defined functions are created by you, the programmer.

6 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).

7 FORMAT NOTE: Please have all of your functions end with return.

8 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

9 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.

10 #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; }

11 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

12 #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; }

13 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;

14 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.

15 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; }

16 //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!

17 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.

18 //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

19 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 }

20 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.

21 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

22 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.

23 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

24 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 0- 127. Treats 128-255 as non-ASCII. 4. isdigit( )returns TRUE if the argument is a digit 0 - 9 5. 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).

25 toascii( ) converts the argument (an arbitrary integer) to a valid ASCII character number 0-127. 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.

26 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.

27 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

28 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.

29 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)

30 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;

31 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.

32 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.

33 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;

34 ** 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;

35 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."


Download ppt "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:"

Similar presentations


Ads by Google