review 2 - chapter 3 and 4 u function 1 u function 2 u function 3 u function 4 u function 5 u...

Download Review 2 - Chapter 3 and 4 u Function 1 u Function 2 u Function 3 u Function 4 u Function 5 u Recursion 1 u Recursion 2 u Array 1 u Array 2 u Array 3 Dr

If you can't read please download the document

Upload: drusilla-gordon

Post on 28-Dec-2015

237 views

Category:

Documents


0 download

TRANSCRIPT

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

  • Mathematical Library FunctionsFunction Name & Argument(s) Descriptionint abs(int i) Absolute value of idouble fabs(double d) Absolute value of ddouble pow(double d1, double d2) d1 raised to d2 powerdouble exp(double d) e raised to d powerdouble sqrt(double d) square root of ddouble 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 ddouble log10(double d) Common log of d Completing the Basic Dr. Ming Zhang

  • Mathematical Library Functions ExamplesExample Returned Valueabs( -3) 3fabs(-7.362) 7.362000pow(2.0, 5.0) 32.000000exp(-3.2)0.040762sqrt(16.0)4.000000sin(0.0) 0.000000cos(0.0)1.000000log(18.697)2.928363log10(18.697) 1.271772 Completing the Basic Dr. Ming Zhang

  • Program Components in C++*Models in C++- Functions- Classes* Functions- Pre-packaged functionC++ standard library functions- Programmer-defined functionsThe programmer writes Dr. Ming Zhang

  • Function Call* Function CallThe 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

  • Function Relationship

    main( )

    function1 function2 function3

    function11 function12 function31

    function111 function112 function311 Dr. Ming Zhang

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

  • Format of Function Definition* Format of Function Definitionreturn-value-type function-name (parameter-list) {declarationsstatements} * Exampleint square (int y){ return y*y;} Dr. Ming Zhang

  • 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 statementreturn; Function does not return a result.* If function does return a result, the statementreturn expression;returns the value of expression to the caller. Dr. Ming Zhang

  • 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

  • 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

  • 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

  • Date Type (from highest to lowest ) Data Type Minimum MaximumLong double system defineddouble system definedfloat system definedunsigned long int 0 4294967295 long int -2147483647 +2147483647unsigned int 0 65535int -32767 +32767unsigned short int 0 65535short int -32767 +32767unsigned char 0 255char -127 +127 Dr. Ming Zhang

  • 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

  • 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

  • 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 .Equal ProbabilityIf 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

  • Scaling: Operator (%) and rand( ) Why use % and rand( ) togetherThe 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( ) % 2Rolling a six-sided die would require random integers in range 1 to 6 1 + (rand( ) % 6) Dr. Ming Zhang

  • Randomizing Pseudo-Random NumberCalling 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.RandomizingFunction can be conditioned to produce a different sequence of random for each execution. Dr. Ming Zhang

  • 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 unsigned int value for srand( )0 to 655350 to 4294967295 Dr. Ming Zhang

  • Identifier (static int x = 50)

    Storage Class Scope Linkage

    Automatic Static Block Scope .........

    auto(local) register(local) extern(global) static(local) Dr. Ming Zhang

  • Automatic Storage Class Automatic Storage Class- auto- registerAutomatic 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

  • Auto - Automatic Storage Class Only variable can be of automatic storage classLocal 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

  • registerData 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 computers 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

  • Static Storage Class Static Storage Class- extern- staticStatic 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

  • Static Storage Class and ScopeEven 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

  • Global Variable and FunctionGlobal 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

  • Local Variable and FunctionLocal 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

  • extern and static externGlobal variables and function names default to storage class specifier externExample extern void a( void); extern int x = 1;staticLocal variables declared with the storage class specifier static.Examplestatic int x = 50; Dr. Ming Zhang

  • 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 valueExamplesvoid function1( ){ cout
  • Inline FunctionsFunction calls involve execution-time overhead. C++ provides inline functions to help reduce function-call overhead - especially for small functions.The qualifer inline before a functions return type in the function definition advises the compiler to generate a copy of the functions code in place (when appropriate) to avoid a function call -saving running time.Exampleinline double cube(const double s) { return s*s*s;} Dr. Ming Zhang

  • Function Call-by-ValueWhen an argument is passed call-by-value, a copy of arguments value is made and passed to called function.Changes to the copy do not affect the original variables value in the caller.This prevents the accidental side effects.Example...double cube(const double s) { return s*s*s;}...cin >> side;cout
  • Function Call-by- ReferenceWith call-by-reference, the caller gives the called function the ability to access the callers 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 parameters type in the function prototype by an ampersand (&); use the same convention when listing the parameters type in the function header. Dr. Ming Zhang

  • Reference for Other VariablesReference 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

  • Default ArgumentsFunction 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 callDefault arguments can be constant, global variables, or function calls.Default arguments must be the rightmost (trailing) argument in a functions parameter list.The default values should only be defined in the function prototype. Dr. Ming Zhang

  • Function OverloadingC++ 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

  • Recursive Function Recursive FunctionRecursive function is a function that calls itself either directly or indirectly through another function.Base CaseThe 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

  • Fibonacci Sequence

    The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21......., 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) = 0fib(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

  • Recursive Calls to Function fibonacci f(3)

    f(2) + f(1)

    f(1) + f(0) return 1

    return 1 return 0 Dr. Ming Zhang

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

  • ArrayArrayAn 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 arrayExample of Array c[12] Dr. Ming Zhang

  • Zeroth ElementThe Zeroth ElementThe first element in every array is the zeroth element.Example of the Zeroth Elementc[0]c[1] is the second element in the array cIn general, the ith element of array c is refereed to as c[i-1]. Dr. Ming Zhang

  • Subscript of ArrayThe 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 Subscripta = 5; b = 6; c[11] = 5; c[a+b] += 2; (c[11] ==7) Dr. Ming Zhang

  • Declaring ArraysData 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

  • 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

  • Passing Array : Call-by-ReferenceC++ 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

  • Passing Array Element: Call-by-ValueAlthough 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

  • Bubble SortScan 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

  • MeanThe 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

    Exampletotal: 681number of data items: 99mean= total/(number of data items) = 681/99 =6.8788

    Dr. Ming Zhang

  • MedianThe median is element n/2 of the sorted n element array.

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

  • ModeThe mode is the most frequent value.

    Exampleif 8 has been occurred 27 time, which is the most frequent value, then the mode is 8. Dr. Ming Zhang

  • Linear SearchThe 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

  • Binary SearchThe 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