Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.

Slides:



Advertisements
Similar presentations
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Functions 1. Example: Power, Square Root and Absolute values of a number #include … float num; float power, squareRoot, absolute; cout
Introduction to Functions Programming. COMP102 Prog Fundamentals I: Introduction to Functions /Slide 2 Introduction to Functions l A complex problem is.
Functions CS 308 – Data Structures. Function Definition Define function header and function body Value-returning functions return-data-type function-name(parameter.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
Overview creating your own functions calling your own functions.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 7 Functions.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions Why we use functions C library functions Creating our own functions.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
VARIABLES AND DATA TYPES Chapter2:part1 1. Objectives: By the end of this section you should: Understand what the variables are and why they are used.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 10/18/04CS150 Introduction to Computer Science 1 Functions Divide and Conquer.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Instructor - C. BoyleFall Semester
CHAPTER 6 USER-DEFINED FUNCTIONS Made By- Kartik Belwal.
1 MODULAR DESIGN AND ABSTRACTION. 2 SPECIFYING THE DETAILS OF A PROBLEM INTO A RELATED SET OF SMALLER PROBLEMS.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
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.
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
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.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Basic concepts of C++ Presented by Prof. Satyajit De
Introduction to C++ computers and programming
User-Defined Functions
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Return_DT F_name ( list of formal parameters)
Value returning Functions
CS150 Introduction to Computer Science 1
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Chapter 6: User-Defined Functions I
Functions Divide and Conquer
In C Programming Language
Fundamental Programming
CS150 Introduction to Computer Science 1
Programming fundamentals 2 Chapter 1: Functions (Sub-Algorithms)
Functions Imran Rashid CTO at ManiWeber Technologies.
Introduction to Functions
Programming Fundamental
Presentation transcript:

Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions

Prof. amr Goneid, AUC2 Functions

3 Functions Predefined (Library) Functions Modular Programming with Functions Types of Functions Function Prototype Declaration Function Definition Formal & Actual Parameters Who Sees Who: Scope of an Identifier Parameter Passing

Prof. amr Goneid, AUC4 1. Predefined Functions Example: #include void main() { cout << ”Square Root. Ex: sqrt(9.0) = ” << sqrt(9.0) << endl; cout << ”Powers. Ex: pow(3.0, 4.0) = ” << pow(3.0,4.0) << endl; cout << ”Absolute Value for int. Ex: ” << ”abs(-9) = ” << abs(-9) << endl; cout << ”Absolute Value for long. Ex: ” << ”labs(-900) = ” << labs(-900) << endl;

Prof. amr Goneid, AUC5 cout << ”Absolute Value for double. Ex: ” << ”fabs(-9.5) = ” << fabs(-9.5) << ”\n”; cout << ”Ceiling (round up). Ex: ceil(4.1)” << ” = ” << ceil(4.1) << endl; cout << ”Floor (round down). ” << ”Ex: floor(4.7) = ” << floor(4.7) << endl; } Square Root. Ex: sqrt(9.0) = 3.0 Powers. Ex: pow(3.0,4.0) = 81 Absolute Value for int. Ex: abs(-9) = 9 Absolute Value for long. Ex: labs(-9000) = 9000 Absolute Value for double. Ex: fabs(-9.5) = 9.5 Ceiling (round up). Ex: ceil(4.1) = 5 Floor (round down). Ex: floor(4.7) = 4 Output:

Prof. amr Goneid, AUC6 2. Modular Programming with Functions Level Main Function Function1 Function2 Function3 Function4Function Functions are natural building blocks for modular programming

Prof. amr Goneid, AUC7 C++ Program Structure Compiler Directives Function Prototypes int main ( ) { Main Data Declarations Main Actions } Used Functions Defined Here C++ program contains function prototype declarations and function definitions. The main is just another function.

Prof. amr Goneid, AUC8 Functions & The Main Function A function is invoked by another function (e.g main) int main( ) main Data Area Main Body Invoke function Next action Function Header Local Data Area Function Body

Prof. amr Goneid, AUC9 3. Types of Functions Input Params Typed Function void Function Action Output Params Returns a Single Scalar Value

Prof. amr Goneid, AUC10 4. Function Prototype Declaration Syntax: (formal parameter list) ; Examples: int cube ( int n ) ; // A function receiving an int parameter (n) and returning an int value. float minxy ( float x, float y ) ; // A function receiving two float parameters ( x, y ) and returning a float value.

Prof. amr Goneid, AUC11 Prototype Declaration (Examples) void printchar ( char c, int n ) ; // a function receiving two parameters ( c, n ) and returns nothing. It is supposed to do an action, e.g. print n of char c on one line. void errormessage ( ) ; // a function receiving nothing and returning nothing. It is supposed to do an action, e.g. print a fixed error message.

Prof. amr Goneid, AUC12 5. Function Definition ( List of Formal Parameters) { Local Data Declarations Function Actions (Executable Statements) }

Prof. amr Goneid, AUC13 Building Typed Functions Syntax: (formal params) { Local Data Area Function Body contains a statement: return ; }

Prof. amr Goneid, AUC14 Example of an Integer Function Function to return the larger of two integer numbers a and b. int maxab ( int a, int b ) { //Does not need Local Data return ( (a >= b) ? a : b ); }

Prof. amr Goneid, AUC15 Example of a Real Function Function to return the area of a circle of radius r. float area ( float r ) { // Local Data const float pi = ; // Action return ( pi * r * r ) ; }

Prof. amr Goneid, AUC16 Example of a Boolean Function Function to return true if an integer n is even and false otherwise. bool iseven ( int n ) { //Does not need Local Data return ( n % 2 == 0 ) ; }

Prof. amr Goneid, AUC17 Example of Using a Typed Function // Prints if an entered integer is even or odd # include using namespace std; // Function used…. bool iseven ( int n ); int main ( ) { int num; cout << “ Enter an integer number: “; cin >> num;

Prof. amr Goneid, AUC18 Example of Using a Typed Function if ( iseven ( num ) ) cout << “ Number is even ! “ ; else cout << “ Number is odd ! “; return 0 ; } // Returns true if an integer is even, false otherwise bool iseven ( int n ) { return ( n % 2 == 0 ); }

Prof. amr Goneid, AUC19 Type of Returned Value Type of a value returned by a called function must be consistent with the type expected by the caller as identified in the function prototype declaration.

Prof. amr Goneid, AUC20 Building void Functions Syntax: void (formal params) { Local Data Area Function Body does not contain a return statement }

Prof. amr Goneid, AUC21 Example of a void Function Action: Fill screen with blanks. void blankscreen( ) { const char blank = ‘ ’ ; int row, col ; for (row = 1; row <= 25; row++) { for (col = 1; col <= 80; col++) cout << blank ; cout << endl; }

Prof. amr Goneid, AUC22 Example of a void Function Action: Write n dashes on a line. void dashes( int n ) { const char dash = ‘-’ ; int i ; for (i = 1; i <= n; i++) cout << dash ; }

Prof. amr Goneid, AUC23 Example of Using a void Function // Prints numbers and dashes # include using namespace std; // Function used…. void dashes ( int n ); int main ( ) { float salary, bonus; cout > salary; bonus = 0.1 * salary ;

Prof. amr Goneid, AUC24 Example of Using a void Function cout << “Bonus ” ; dashes(3); cout << bonus; dashes(5); cout << endl; return 0 ; } // Writes n dashes on one line void dashes ( int n ) { const char dash = ‘-’ ;int i ; for (i = 1; i <= n; i++) cout << dash ; }

Prof. amr Goneid, AUC25 6. Formal & Actual Parameters In Function Declarations: bool iseven(int n);int maxab( int a, int b ) void dashes(int n); a,b,n are FORMAL parameters(Dummies or Gates). They are LOCAL to their modules. When invoked in a main function: maxab(x,y) or maxab(1+z,2.3) dashes(7); dashes(k);iseven ( num ) x, y, 1+z, 2.3, 7, k, num are ACTUAL parameters passed from main to modules through their respective gates.

Prof. amr Goneid, AUC26 Key Points Ê The substitution of the value of an actual parameter in a function call for its corresponding formal parameter is strictly positional. That is, the value of the first actual parameter is substituted for the first formal parameter; the second and so on

Prof. amr Goneid, AUC27 Key Points Ë The names of these corresponding pairs of parameters are no consequence in the substitution process. The names may be different, or they may be the same. Ì The substituted value is used in place of the formal parameter at each point where that parameter appears in the called function.

Prof. amr Goneid, AUC28 Passing values of Actual Parameters main maxab main iseven a b n num x y

Prof. amr Goneid, AUC29 Formal & Actual Parameters Correspondence between actual and formal parameters is determined by position in their respective lists. These lists must be the same size. The names of corresponding actual and formal parameters may be different. Formal parameters and corresponding actual parameters should agree with respect to type.

Prof. amr Goneid, AUC30 Overloaded Functions: #include float average(float x, float y); // Returns the average of x and y float average(float x, float y, float z); // Returns the average of x, y, and z void main() { cout << ”The average of 3.0 and 7.0” << ” is ” << average(3.0, 7.0) << endl; cout << ”The average of 3.0, 4.0, and 8.0” << ” is ” << average(3.0, 4.0,8.0) << endl; }

Prof. amr Goneid, AUC31 float average(float x, float y) { return ((x + y)/2.0); } float average(float x, float y, float z) { return ((x + y + z)/3.0); } The average of 3.0 and 7.0 is The average of 3.0, 4.0, and 8.0 is Output:

Prof. amr Goneid, AUC32 7. Who Sees Who: Scope of an Identifier To see = to recognize = to be able to use, invoke, change, etc. Scope = the domain in which an identifier is recognizable. The scope of an identifier extends only from the point where it is defined to the end of the module in which it is defined. A module can see itself (Recursion)

Prof. amr Goneid, AUC33 Scope(continued) Global : can be seen by all modules. Local: can be seen only by its module but not by other modules. Names declared inside a function/main are local to that function/main. Anything declared before the main function is global. It can be called anywhere in the program. Hence, all functions are global. For two things having the same id, local overrides global.

Prof. amr Goneid, AUC34 Scope(example) Module A Data P, Q Module B Data x, w Module C Data m, n Main Data x, y Prototypes of A, B, C int x, m; // Global Variables

Prof. amr Goneid, AUC35 A function to swap two characters. // x and y are passed by value void swap (char x, char y) { char temp; temp = x; x = y; y = temp; } 8. Parameter Passing: Example of a Paradox

Prof. amr Goneid, AUC36 Paradox (continued) A program uses the function to swap two characters: void swap (char x, char y); int main ( ) { char a,b ; a = ‘M’ ; b = ‘N’ ; cout << a << ‘ ‘ << b << endl; swap(a,b); cout << a << ‘ ‘ << b << endl; } No Change! Why ? M N

Prof. amr Goneid, AUC37 Where in Memory? The DOS Memory Map: one segment = 64 kbyte DS = Data Segment (Data) CS = Code Segment ( Main & Modules code) SS = Stack Segment (System Stack) Heap = Rest of DOS memory DOSCSDSSSHEAP LM HM

Prof. amr Goneid, AUC38 Parameter Passing: What Really Happened Memory BeforeMemory After ‘N’ ‘M’ ‘N’ ‘M’a b a b Swap addr ‘M’ -> x ‘N’-> y Swap addr ‘N’ <- x ‘M’ <- y DSSSDSSS

Prof. amr Goneid, AUC39 To see the change, pass the address, not the value ! Memory BeforeMemory After ‘N’ ‘M’ ‘N’a b a b Swap addr Addr of a Addr of b Swap addr Addr of a Addr of b DSSSDSSS

Prof. amr Goneid, AUC40 How to pass the Address (pass by Reference) The correct function to swap two characters. // x and y are passed by reference void swap (char& x, char& y) { char temp; temp = x; x = y; y = temp; } // symbol & means address of

Prof. amr Goneid, AUC41 Passing by Reference (continued) A program uses the function to swap two characters: void swap (char& x, char& y); int main ( ) { char a,b ; a = ‘M’ ; b = ‘N’ ; cout << a << ‘ ‘ << b << endl; swap(a,b); cout << a << ‘ ‘ << b << endl; } Now there is Change! M N N M

Prof. amr Goneid, AUC42 Parameter Passing: Summary Input Only Parameters: those you do not want to change- pass by value Output Only Parameters: those you want to see what happened to them – pass by reference (address) using &. Input/Output Parameters: pass by reference using &.