Chapter 4 Procedural Abstraction and Functions That Return a Value.

Slides:



Advertisements
Similar presentations
Functions  Programmer-Defined Functions  Local Variables in Functions  Overloading Function Names  void Functions,  Call-By-Reference Parameters in.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 ; Programmer-Defined Functions Two components of a function definition.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
CS 201 Functions Debzani Deb.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Chapter 6: User-Defined Functions I
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
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 6: Functions.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Top-Down Design SLO1.8 Explain the benefits of dividing large programming tasks to smaller.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
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.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
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.
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.
Chapter 6: User-Defined Functions I
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
User Defined Functions
6 Chapter Functions.
Chapter 6: User-Defined Functions I
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Predefined Functions Revisited
Single-Result Functions & Modularity
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Chapter 4 Procedural Abstraction and Functions That Return a Value

Procedural Abstraction abstraction: the separation of properties from the actual physical object. procedural abstraction: separate what the function does from how it does it.

Top Down Design Working from the general to the specific Divide and Conquer –Breaking down a problem into sub problems and subtasks. –Each subtask is a complete structure that accomplishes a specific well defined task. –C++ uses functions to complete each task

Function A body of code to perform a specific task. A function that performs a single well- defined task is called a cohesive function.

Predefined Functions (Libraries) In order to keep the compiler small, C++ groups functions into Libraries that we can include when we need them. Library files are called header files. (.h) When we use the #include directive, the compiler copies the code of the header file into your program. Examples: Contains functions used to do input and output Contains functions used to do mathematical computations

How To Use Predefined Functions Include the library Use the function name in a function call. Function call: –We invoke the function by giving its name and all relevant information (arguments). –Control passes to the function code, executes it, returns a value (if any) and returns control to the calling function.

Type Casting static_cast is a predefined function that changes type. –The use of denotes the new type used to replace the existing type. Example: int sum, count; double average; average = static_cast (sum)/count; Be sure to put parenthesis around single argument to prevent integer divide and then casting. Older form: type (variable) average = double (sum)/count;

Programmer Defined Functions Your own functions. Consists of a two parts: –the function prototype/declaration –the function definition. A function is like a small program; it has a body and may return a value.

Function As A Small Program Calling a function is as running a small program. Functions use formal parameter, rather than cin, for input. The arguments to the function are the inputs and they are plugged in the formal parameters. Functions can send their outputs to the caller through the return statement.

Function prototype/declaration Syntax: Type_Returned Function_Name (Parameter_List); Functions must be declared before use. Funtion Prototype (FP) associates the function name with the code. FP tells what type of information is needed (order and type of input arguments) and determines what type of value it returns (type of result). FP has a semicolon at the end. Parameters the list separated by commas. Example: int get_choice (); // empty parameter list double compute_area (double len, int wid); Always include a comment with the prototype telling what its purpose is. A good function is cohesive - it accomplishes a single, well-defined task.

Function prototype/declaration (cont.) Formal parameters: placeholder for the real variable – sometimes called dummy parameters. Ex: bool inRange (int choice); Only the type of the variables needs to be in the parameter list so formal parameters can be omitted in the prototype but the type must be specified. (not advised) Ex: bool inRange (int); FP’s may be anywhere in a program but before the function call. –Above main: the whole program can see and use them –Inside another function: only that function can see and use them –In a header file: Any file including that file can use them

Function Definition Contains 2 part: function header and function body Must have formal parameters listed in the function header May (usually) be defined: –Below main –In another.cpp file which is linked to the main program file Cannot be within another function Functions that return a value has a returned type and a value of that type is computed in the program and is passed back to the calling program by the return statement.

Function Definition (Actual code) Syntax: Type_Returned Function_Name (Parameter_List) // function header { … // function body }

Function Call Syntax: aValue = Function_Name (Argument_List); The argument list is a way for functions to communicate with each other by passing information. When the function is called, the program jumps to the function code and executes it. A function is like a small program

Functions that return a boolean value Often used as a flag to decide what action to take next based on evaluation of a certain condition. Example: bool inRange (int choice) { if ((choice 0)) return true; else return false; }

Passing information into the function (Call-by-Value) When the function needs information from the main program or another function to work. The function will use the values but not change them. The compiler actually makes a copy of the value to use. The compiler matches the actual parameters to the dummy parameters in the order given in the function call. If you reverse the order, your program will NOT tell you!!! –int result = subtraction (5, 3); –int result = subtraction (3, 5);

Functions with Call_by_Value parameters Syntax: Type_returned Function_Name (type para1, …, type paraN); The real variables (actual parameters) in the function call are matched with the formal parameters by the order. A copy of the value of the variables replaces the formal parameters in the function body. Automatic type conversion by implicit conversion through parameter list. Call-by-value: –The initial value is protected. –A copy of the value of the actual parameters is used in the function but the function cannot change the value of the actual variables. Constants and expressions can be passed into functions using call- by-value. The value computed in the function is sent back to the calling function by the return statement. The function call thus has a value and can be used in computations, etc.

Call_by_Value (Example) #include using namespace std; int sum (int left, int right);// Function prototypes int main () { int x, y; // Declare two variables to hold integers cout << "Enter two integers.. seperated by a space: "; // User prompt cin >> x >> y; cout << "The sum of the two numbers " << x << " " << y << " is “ << sum(x, y); // Function call cout << endl; return 0;// This program requires a return integer value } { int result = left + right; left++; right++; return result; } Function definition int sum (int left, int right) Function header Function body

Call_by_Value Mechanism Beginning ? ? ? ? xyabxyab cin >> x >> y; User enter 3 and 4 sum (x, y);  sum (3, 4)

Why use functions? To avoid Duplicate code: –If process needed repeatedly, only code once, call multiple times. (Error checking). –Can also use in other programs. –Shortens program code. To improve maintainability –By improving readability, use descriptive function names –Smaller modules allow easier changes To improve modularity, easier to write. –Small tasks easier than larger tasks: Do small parts and link together. –Allows many programmers to work on one program. Portability. –Can also use in other programs. Clarity –Each subtask clearly defined and their relationship to other parts is clear.

When to use a function Operation is used in two or more separate places in a program. –(Company name and address used repeatedly) When operation needs to serve more than 1 program. –(need Company name and address in several programs - use user-made library) Operation returns a single value –(calculate total cost) Operation can be described as a distinct task –(produce summary output at end of program) Program is too long and can be program into separate operations.

Functions (Need to Know) Must use consistent variable names and constants (usually a system glossary or kept in project library that all use). Must understand data flow between functions. Must verify flow between functions (order)

Procedural Abstraction The separation of what the function does from how it does it: (Black Box Analogy) We can give structure and order of calling functions without knowing how they do computations. Just need to know what they do, what they need to do it; not how they work. (information hiding)

Procedural Abstraction (Information) Comments: information for the users. –Pre-conditions: Any and all conditions required of the arguments to the function –Post-conditions: Describe the value that is returned Ex: double ConvertCoins (int number, double coinValue); // Pre-Cond: Get number of coins of 1 type and their value in dollar. // Post-Cond: The total amount of money converted to dollars and returned. int ConvertCoins (int number, int coinValue); // Pre-Cond: Get number of coins of 1 type and their value in cents. // Post-Cond: The total amount of money converted to cents and returned.

Formal Parameter Names Type_returned Function_Name (type para1, …, type paraN); –para1, … paraN are formal parameter names Should be descriptive but not too long. Often have a descriptive suffix like “_par” or prefix like “f_” or “p” double ConvertCoins (int pNumber, double pCoinValue); Can be specific or general depending on the use of the functions. Declarations of variables inside the function do not include the formal parameters.

Global Variables A function is like a small program. Each function is called a block of code. Variables declared in main are global to main and can be seen inside main (scope). Variables declared above main are global to all and can be seen by any files linked to the main file.

Local Variables A local variable/constant is declared inside a block designated by {}. –Scope: Local data is hidden from any other block/function. Cannot be corrupted. If there is a variable with the same name in main, the local variable takes name precedence inside the function. –Visibility: Local data exists only during function call. Dies on exit.

Global and Local Variables #include using namespace std; double area (double); double PI = ; // global variable int main () { int rad;// Declare a variables to hold radius, local to main cout << "Enter the radius of the circle: "; // User prompt cin >> rad; cout << "The area of the circle with radius " << rad << " is “ << area (rad); // Print out a complete report to the screen cout << endl; return 0;// This program requires a return integer value } double area (double pRadius) { double rad = pRadius; return rad*rad*PI; }

General Notes on Function Scope The scope of definition of a function is from the function header to the } brace (closing brace). Local Identifiers defined within that scope are only visible within that scope. Different functions can use the same identifiers without conflict. Formal parameter names may have the same name or a different name from the actual variables used in the function call. It doesn’t matter. The compiler uses position to decide which value is used in which formal parameter. Actual variables must be the same type as the formal parameters they replace (type consistent) or standard conversion rules apply (dangerous). For clarity and maintainability, we place all include directives together, followed by all global named constant declarations together, followed by all function prototypes. Formal parameters in functions are local to the function. Thus, when we plug in actual parameters, the changes to those parameters are only in effect within the function and will not be permanently changed.

Overloading A Function Name C++ allows identically named functions within the same scope if the number and type of parameters can distinguish them. It is called OVERLOADING. If there are multiple definitions of a function f, then f is considered to be overloaded. Ex: int Sum (int n1, int n2); int Sum (int n1, int n2, int n3); int Sum (int n1, int n2, int n3, int n4); The compiler determines which version of an overloaded function to invoke by matching the number and type of parameters in the function prototype with the function call.

Overloaded Functions Functions with the same name but different parameter list. double ConvertCoins (int number, double coinValue); // Pre-Cond: Get number of coins of 1 type and their value. // Post-Cond: The total amount of money converted to dollars. int ConvertCoins (int number, int coinValue); // Pre-Cond: Get number of coins of 1 type and their value in cents. // Post-Cond: The total amount of money converted to cents. int ConvertCoins (int number, double coinValue); // Pre-Cond: Get number of coins of 1 type and their value. // Post-Cond: The total amount of money converted to cents. NOT an overloaded function