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

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7: User-Defined Functions II
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
An Introduction to Programming with C++ Fifth Edition
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
Function (L16) * Mathematical Library Functions * Program Components in C++ * Motivations for Functionalizing a Program * Function Prototype * Function.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 2007 Pearson Education, Inc. All rights reserved C Functions.
CPSC230 Computers & Programming I Lecture Notes 20 Function 5 Dr. Ming Zhang.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Function 2 (L17) * Function Prototype * Promotion Rules * Data Type * Library Header File * Customer Header File * Case Study * Exercise/Home Work Dr.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
1 Lecture 3 Part 1 Functions with math and randomness.
Function. Introduction Library function New defined function Random number generator Scope Inline function Function overload Function Function.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2006 Pearson Education, Inc. All rights reserved Functions and an Introduction to Recursion.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
Functions.
Functions and an Introduction to Recursion
CSC113: Computer Programming (Theory = 03, Lab = 01)
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
C++ for Engineers and Scientists Second Edition
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

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

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

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

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

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

Function Relationship main( ) function1 function2 function3 function11 function12 function31 function111 function112 function311 Dr. Ming Zhang

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

Format of Function Definition return-value-type function-name (parameter-list) { declarations statements } * Example int 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 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

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 Maximum Long double system defined double system defined float system defined unsigned long int 0 4294967295 long int -2147483647 +2147483647 unsigned int 0 65535 int -32767 +32767 unsigned short int 0 65535 short int -32767 +32767 unsigned char 0 255 char -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 <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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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