Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review 2 - Chapter 3 and 4 Function 1 Function 2 Function 3 Function 4

Similar presentations


Presentation on theme: "Review 2 - Chapter 3 and 4 Function 1 Function 2 Function 3 Function 4"— Presentation transcript:

1 Review 2 - Chapter 3 and 4 Function 1 Function 2 Function 3 Function 4
Recursion 1 Recursion 2 Array 1 Array 2 Array 3 Dr. Ming Zhang

2 Mathematical Library Functions
Function Name & Argument(s) Description int abs(int i) Absolute value of i double fabs(double d) Absolute value of d double pow(double d1, double d2) d1 raised to d2 power double exp(double d) e raised to d power double sqrt(double d) square root of d double sin(double d) Sine of d(d in radians) double cos(double d) Cosine of d(d: radians) double log(double d) Natural log of d double log10(double d) Common log of d Completing the Basic Dr. Ming Zhang

3 Mathematical Library Functions Examples
Example Returned Value abs( -3) fabs(-7.362) pow(2.0, 5.0) exp(-3.2) sqrt(16.0) sin(0.0) cos(0.0) log(18.697) log10(18.697) Completing the Basic Dr. Ming Zhang

4 Program Components in C++
*Models in C++ - Functions - Classes * Functions - Pre-packaged function C++ standard library functions - Programmer-defined functions The programmer writes Dr. Ming Zhang

5 Function Call * Function Call
The function call specifies the function name and provides information (as arguments) that the called function needs to do its job. And the called function returns the result to calling function (caller) * Example …… double time, height; height = 800.0; time = sqrt( 2.0 * height/32.2 ); Dr. Ming Zhang

6 Function Relationship
main( ) function function function3 function function function31 function function function311 Dr. Ming Zhang

7 Function Prototype * Function Prototype
return-value-type function-name( data-type list) * Example of Function Prototype int square (int ) * The function prototype is not required if the definition of the function appears before the function’s first use in the program. In such case, the function definition also acts as the function prototype. Dr. Ming Zhang

8 Format of Function Definition
return-value-type function-name (parameter-list) { declarations statements } * Example int square (int y) return y*y; Dr. Ming Zhang

9 Three Returns of a Function
* Control is returned simple when the function-ending right brace is reached. Function does not return a result. * Executing the statement return; Function does not return a result. * If function does return a result, the statement return expression; returns the value of expression to the caller. Dr. Ming Zhang

10 Function Prototype A function prototype tells the compiler
* the name of the function, * the type of data returned by the function, * the number of parameters the function expects to receive, * the types of the parameters, and * the order in which these parameters are expected. Dr. Ming Zhang

11 Promotion Rules * The promotion rules apply to expressions containing values of two or more data types (mixed-type expression). * The type of each value in a mixed-type expression is promoted to the highest type in the expression ( Actually a temporary version of each value is created and used for the expression - the original values remain unchanged). Dr. Ming Zhang

12 Common Use of Promotion
* A common use of promotion is when the type of an argument to a function does not match the parameter type specified in the function definition. * The type of an argument to a function is promoted to the highest parameter type specified in the function definition. Dr. Ming Zhang

13 Date Type (from highest to lowest )
Data Type Minimum Maximum Long double system defined double system defined float system defined unsigned long int long int unsigned int int unsigned short int short int unsigned char char Dr. Ming Zhang

14 Library Header Files * Each Standard library has a corresponding header file containing the function prototypes for all the functions in the library and definition of various data types and constants needed by those functions. * The header files ending in “.h” are “old-style’ header files. * The new-style header files do not use “.h”. Dr. Ming Zhang

15 Custom Header Filers * The programmer can create custom header files.
* Programmer-defined header files should end in “.h”. * A programmer-defined header file can be included by using the #include preprocessor directive. * Example #include “square.h” Dr. Ming Zhang

16 Random Number Generation
Function rand( ) The function rand( ) generates an unsigned integer between 0 and RAND_MAX. RAND_MAX (at least 32767) A symbolic constant defined in the <cstdlib>. Equal Probability If rand( ) truly produces integers at random, every number between 0 to RAND_MAX has an equal chance (probability) of being chosen each time rand( ) is called Dr. Ming Zhang

17 Scaling: Operator (%) and rand( )
Why use % and rand( ) together The range of values produced directly by rand( ) is often different than what is needed in the specific application. Coin Tossing 0 for “heads” and 1 for “tails” rand( ) % 2 Rolling a six-sided die would require random integers in range 1 to 6 1 + (rand( ) % 6) Dr. Ming Zhang

18 Randomizing Pseudo-Random Number
Calling rand( ) repeatedly produces a sequence of numbers that appears to be random. However, the sequence repeats itself each time the program is executed. So function rand( ) actually generates pseudo-random number. Randomizing Function can be conditioned to produce a different sequence of random for each execution. Dr. Ming Zhang

19 srand( ) srand( ) Function srand( ) takes an unsigned integer argument and seeds the rand( ) function to produce a different sequence of random numbers for each execution of the program #include <cstdlib> unsigned int value for srand( ) 0 to 65535 0 to Dr. Ming Zhang

20 Identifier (static int x = 50) Storage Class Scope Linkage
Automatic Static Block Scope auto(local) register(local) extern(global) static(local) Dr. Ming Zhang

21 Automatic Storage Class
- register Automatic Storage Class Variable - Such variables are created when the block in which they are declared is entered. - They exist while the block is active. - They are destroyed when the block is exited. Dr. Ming Zhang

22 Auto - Automatic Storage Class
Only variable can be of automatic storage class Local variables are of automatic storage class by default, so keyword auto is rarely used. Refer to variables of automatic storage class simple as automatic variables. Example int squr( auto int x ) { auto int y; cin >> y; return( x*x = y); } Dr. Ming Zhang

23 register Data in the machine-language version of a program are normally loaded into register for calculations and other processing. The register variable suggests that the variable be placed in one of computer’s registers, regardless of whether the compiler does this. The register keyword can be used only with local variables and function parameters. Example register int counter = 1; Dr. Ming Zhang

24 Static Storage Class Static Storage Class - extern - static
Static Storage Class Variable - Such variables and functions exist from the point at which the program begins execution. - For variables, storage is allocated and initialized once when the program begins execution. Dr. Ming Zhang

25 Static Storage Class and Scope
Even though the variables and function names exist from the start of program execution, this does not mean that these identifiers can be used throughout the program. Storage class and scope (where a name can be used ) are separate issues. Dr. Ming Zhang

26 Global Variable and Function
Global Variables are created by placing variable declarations outside any function definition. Global variables retain their values throughout the execution of the program. Global variables and functions can be referenced by any function that follows their declarations or definitions in the source file. Dr. Ming Zhang

27 Local Variable and Function
Local variables are created by placing variable declarations inside any function definition. Local variables retain their values throughout the execution of the function. Local variables and functions can be referenced inside of the function. Dr. Ming Zhang

28 extern and static extern
Global variables and function names default to storage class specifier extern Example extern void a( void); extern int x = 1; static Local variables declared with the storage class specifier static. static int x = 50; Dr. Ming Zhang

29 Functions with Empty Parameter Lists
In C++, an empty parameter list is specified by writing either void or nothing at all in parentheses. The prototype void print( ); specifies that function print does not take any arguments and does not return a value Examples void function1( ) { cout<<“function1 takes no argument”<<endl;} void function2(void) { cout<<“function2 takes no argument”<<endl;} Dr. Ming Zhang

30 Inline Functions Function calls involve execution-time overhead. C++ provides inline functions to help reduce function-call overhead - especially for small functions. The qualifer inline before a function’s return type in the function definition ”advises” the compiler to generate a copy of the function’s code in place (when appropriate) to avoid a function call -saving running time. Example inline double cube(const double s) { return s*s*s;} Dr. Ming Zhang

31 Function Call-by-Value
When an argument is passed call-by-value, a copy of argument’s value is made and passed to called function. Changes to the copy do not affect the original variable’s value in the caller. This prevents the accidental side effects. Example …... double cube(const double s) { return s*s*s;} cin >> side; cout << “Volume of cube is” << cube(side); Dr. Ming Zhang

32 Function Call-by- Reference
With call-by-reference, the caller gives the called function the ability to access the caller’s data directly, and to modify that data if the called function so choose. A reference parameter is an alias for its corresponding argument. To indicate that a function parameter is passed by reference, simple follow the parameter’s type in the function prototype by an ampersand (&); use the same convention when listing the parameter’s type in the function header. Dr. Ming Zhang

33 Reference for Other Variables
Reference can also be used as aliases for other variables within a function. Once a reference is declared as an alias for another variable, all operations supposedly performed on the alias (the reference) are actually performed on the original variable itself. The alias (the reference) is simply another name for the original variable. Reference variables mush be initialized in their declarations. Dr. Ming Zhang

34 Default Arguments Function calls may commonly pass a particular value of an argument, the programmer can provide a default value for that argument (default argument). When a default argument is omitted in a function call, the default value of that argument is automatically inserted by the compiler and passed in the call Default arguments can be constant, global variables, or function calls. Default arguments must be the rightmost (trailing) argument in a function’s parameter list. The default values should only be defined in the function prototype. Dr. Ming Zhang

35 Function Overloading C++ enables several functions of the same name to be defined as long as these function have different sets of parameters (at least their types are concerned). This capability is called function overloading. Function overloading is commonly used to create several functions of the same name that perform similar tasks, but on different data types. Overloaded functions can have different return types, but must have different parameter lists. Dr. Ming Zhang

36 Recursive Function Recursive Function
Recursive function is a function that calls itself either directly or indirectly through another function. Base Case The simplest case the function actually knows how to solve. Recursive Call (Recursion Step) The function calls a fresh copy of itself to go to work on the smaller problem. Dr. Ming Zhang

37 Fibonacci Sequence The Fibonacci sequence is
0, 1, 1, 2, 3, 5, 8, 13, , where the first two terms are 0 and 1, and each term thereafter is the sum of the two preceding terms; that is fib(0) = 0 fib(1) =1 fib(n) = fib(n-1) + fib(n-2) Using this information, write a program that calculate the nth number in a Fibonacci sequence, where n is interactively entered into the program by the user. For example, if n = 6, the program should display the value 5. Dr. Ming Zhang

38 Recursive Calls to Function fibonacci
f(2) f(1) f(1) f(0) return 1 return 1 return 0 Dr. Ming Zhang

39 fibonacci Function unsigned long fibonacci(unsigned long n) {
if ( n == 0 || n == 1) // base case return n; else // recursive case return fibonacci(n-1) + fibonacci(n-2); } Dr. Ming Zhang

40 Array Array An array is a consecutive group of memory locations that all have the same name and the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array Example of Array c[12] Dr. Ming Zhang

41 Zeroth Element The Zeroth Element
The first element in every array is the zeroth element. Example of the Zeroth Element c[0] c[1] is the second element in the array c In general, the ith element of array c is refereed to as c[i-1]. Dr. Ming Zhang

42 Subscript of Array The position number contained within square brackets is more formally called a subscripts. The subscript must be an integer or integer expression. If a program uses an expression as s subscript, then the expression is evaluated to determine the subscript. Example of Subscript a = 5; b = 6; c[11] = 5; c[a+b] += 2; (c[11] ==7) Dr. Ming Zhang

43 Declaring Arrays Data Type The Brackets (to enclose the subscript)
int c[12]; Semicolon Name of Array Subscript The name of entire array is c. Its twelve elements are named: c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7], c[8], c[9], c[10], c[11] (c[12] ??????) Dr. Ming Zhang

44 Passing Arrays to Functions
To pass an array argument to a function, specify the name of the array without any brackets. When passing an array to a function, the array size is normally passed a well, so the function can process the specific number of elements in the array. Dr. Ming Zhang

45 Passing Array : Call-by-Reference
C++ automatically passes arrays to functions using simulated call-by-reference - the called functions can modify the element values in the callers’ original arrays. The value of the name of the array is the address of the first element of the array. Therefor,when the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original memory locations. Dr. Ming Zhang

46 Passing Array Element: Call-by-Value
Although entire arrays are passed by simulated call-by-reference, individual array elements are passed by call-by-value exactly as simple variables are. The called functions can temporary modify the element values in the called functions, but can NOT modify the element values in the callers’ original arrays. To pass an element of an array to a function, use the subscripted name of the array element as an argument in the function call. Dr. Ming Zhang

47 Bubble Sort Scan through the array,comparing each element with the one following (be careful not to look beyond the end of the array0. If any comparison shows that the earlier element is larger than the later one, exchange the two element. If this process is performed n-1 times, where n is the array size, then the array will be sorted. Dr. Ming Zhang

48 Mean The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items Example total: 681 number of data items: 99 mean= total/(number of data items) = 681/99 =6.8788 Dr. Ming Zhang

49 Median The median is element n/2 of the sorted n element array.
Example n = 99 n/2 = 49 in sorted n element array, the value of element 49 is the median ( say 7). Dr. Ming Zhang

50 Mode The mode is the most frequent value. Example
if 8 has been occurred 27 time, which is the most frequent value, then the mode is 8. Dr. Ming Zhang

51 Linear Search The linear search compares each element of the array with the search key. Since the array is not in any particular order, it is just as likely that the value will be found in the first element as the last. On average, therefor, the program must compare the search key with half the elements of the array for a value in the array. To determine that a value is not in the array, the program must compare the search key to every element in the array. Dr. Ming Zhang

52 Binary Search The binary search algorithm eliminates one-half of the elements in the array being searched after each comparison. The algorithm locates the middle element of the array and compares it with the search key. If they equal, the search key is found, and the array subscript of that element is returned. Otherwise, the problem is reduced to searching one-half of the array. If the search key is less than the middle element of the array, the first half of the array is searched; otherwise, the second half of the array is searched. The search continues until the search key is equal to the middle elements of a sub-array or not found. Dr. Ming Zhang


Download ppt "Review 2 - Chapter 3 and 4 Function 1 Function 2 Function 3 Function 4"

Similar presentations


Ads by Google