Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.

Slides:



Advertisements
Similar presentations
Chapter 5 Functions.
Advertisements

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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 6: Functions.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
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.
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.
CS102 Introduction to Computer Programming Chapter 6 Functions Part I.
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 6: User-Defined Functions
CS102 Introduction to Computer Programming Chapter 6 Functions Continued.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
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.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
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.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Seventh Edition.
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 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
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.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 Chapter 9 Scope, Lifetime, and More on Functions.
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.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Lecture 5 – Function (Part 2) FTMK, UTeM – Sem /2014.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
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 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Lecture 3 C & C++ programming.
CSCI 161: Introduction to Programming Function
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Addis Ababa Institute of Technology Yared Semu May 2012
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 6: Functions Starting Out with C++ Early Objects
Chapter 9 Scope, Lifetime, and More on Functions
6.12 Default Arguments.
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Functions.
6 Chapter Functions.
Chapter 6: Functions Starting Out with C++ Early Objects Ninth Edition
Chapter 6 – Methods Topics are:
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Instructor: Hidayah Elias Course: COMPUTER PROGRAMMING (BFC 2042)
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Chapter 6 Functions

Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a caller Default formal parameter values Default formal parameter values Functions sending data out to a caller Functions sending data out to a caller Function prototypes Function prototypes Overloading functions Overloading functions More on variables. More on variables.

Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection of statements to perform a task Function: a collection of statements to perform a task Motivation for modular programming: Motivation for modular programming: –Improves maintainability of programs –Simplifies the process of writing programs

Defining and Calling Functions Function call: statement causes a function to execute Function call: statement causes a function to execute Function definition: statements that make up a function Function definition: statements that make up a function

Function Definition Definition includes: Definition includes: –return type: data type of the value that function returns to the part of the program that called it –name: name of the function. Function names follow same rules as variables –parameter list: variables containing values passed to the function –body: statements that perform the function’s task, enclosed in {}

Function Return Type If a function returns a value, the type of the value must be indicated: If a function returns a value, the type of the value must be indicated: int main() If a function does not return a value, its return type is void : If a function does not return a value, its return type is void : void printHeading() { cout << "\tMonthly Sales\n"; }

Calling a Function To call a function, use the function name followed by () and ; To call a function, use the function name followed by () and ;printHeading(); When called, program executes the body of the called function When called, program executes the body of the called function After the function terminates, execution resumes in the calling function at point of call. After the function terminates, execution resumes in the calling function at point of call.

Calling Functions main can call any number of functions main can call any number of functions Functions can call other functions Functions can call other functions Compiler must know the following about a function before it is called: Compiler must know the following about a function before it is called: –name –return type –number of parameters –data type of each parameter

Function Documentation Function definition should be preceded by comments that indicate –Purpose of the function –How it works, what it does –Input values that it expects, if any –Output that it produces, if any –Values that it returns, if any

Function Prototypes Ways to notify the compiler about a function before a call to the function: Ways to notify the compiler about a function before a call to the function: –Place function definition before calling function’s definition –Use a function prototype (function declaration) – like the function definition without the body Header: void printHeading() Header: void printHeading() Prototype: void printHeading(); Prototype: void printHeading();

Prototype Notes Place prototypes near top of program Place prototypes near top of program Program must include either prototype or full function definition before any call to the function – compiler error otherwise Program must include either prototype or full function definition before any call to the function – compiler error otherwise When using prototypes, can place function definitions in any order in source file When using prototypes, can place function definitions in any order in source file

Example #include #include using namespace std; //function declarations void first(); void second(); int main() { cout << “I am starting in function” <<“main. \n”; <<“main. \n”;first();second(); cout << “back in function main again \n”; return 0; } //Definition of function first //this function displays a message void first() { cout << “I am now inside the” << “function first \n”; << “function first \n”;} //Definition of function second //this function displays a message void second() { cout << “I am now inside the” << “function second \n”; << “function second \n”;}

Sending Data into a Function Can pass values into a function at time of call: Can pass values into a function at time of call: c = sqrt(a*a + b*b); Values passed to function are arguments Values passed to function are arguments Variables in function that hold values passed as arguments are parameters Variables in function that hold values passed as arguments are parameters

Other Parameter Terminology A parameter can also be called a formal parameter or a formal argument A parameter can also be called a formal parameter or a formal argument An argument can also be called an actual parameter or an actual argument An argument can also be called an actual parameter or an actual argument

Example #include #include using namespace std; //function declarations void displayValue(int); int main() { cout << “I am passing 5 to ” <<“displayValue. \n”; <<“displayValue. \n”;displayValue(5); cout << “Now I am back in” << “function main \n”; << “function main \n”; return 0; } //Definition of function displayValue //it uses an integer parameter whose //value is displayed. void displayValue(int num) { cout << “the value is ” <<num<<endl; <<num<<endl;}

Parameters, Prototypes, and Function Headings For each function argument, For each function argument, –the prototype must include the data type of each parameter in its () –the header must include a declaration for each parameter in its () void evenOrOdd(int); //prototype void evenOrOdd(int num) //header evenOrOdd(val); //call

Function Call Notes Value of argument is copied into parameter when the function is called Value of argument is copied into parameter when the function is called A parameter’s scope is the function which uses it A parameter’s scope is the function which uses it Function can have > 1 parameter Function can have > 1 parameter There must be a data type listed in the prototype () and an argument declaration in the function header () for each parameter There must be a data type listed in the prototype () and an argument declaration in the function header () for each parameter Arguments will be promoted/demoted as necessary to match parameters Arguments will be promoted/demoted as necessary to match parameters

Calling Functions with Multiple Arguments When calling a function with multiple arguments: –the number of arguments in the call must match the prototype and definition –the first argument will be used to initialize the first parameter, the second argument to initialize the second parameter, etc.

The return Statement Used to end execution of a function Used to end execution of a function Can be placed anywhere in a function Can be placed anywhere in a function –Statements that follow the return statement will not be executed Can be used to prevent abnormal termination of program Can be used to prevent abnormal termination of program Without a return statement, the function ends at its last } Without a return statement, the function ends at its last }

Example #include #include using namespace std; //function declarations void divide(double,double); int main() { double num1,num2; cout << “Enter two numbers and I will divide ” << “the first number by the second \n”; << “the first number by the second \n”; cin >> num1 >> num2; divide ( num1, num2); return 0; } //Definition of function divide //uses two parameters: arg1 and arg2. the // function divides arg1 by arg2 and shows // the results. If arg2 is zero, the function //returns void divide (double arg1, double arg2) { If (arg2 == 0) { cout << “Sorry, I cannot divide by” << “zero \n”; << “zero \n”;return;} cout<< “the result is ” << (arg1/arg2) <<endl; << (arg1/arg2) <<endl;}

Returning a Value From a Function return statement can be used to return a value from function to the point of call return statement can be used to return a value from function to the point of call Prototype and definition must indicate data type of return value (not void ) Prototype and definition must indicate data type of return value (not void ) Calling function should use return value: Calling function should use return value: –assign it to a variable –send it to cout –use it in an expression

Returning a Boolean Value Function can return true or false Function can return true or false Declare return type in function prototype and heading as bool Declare return type in function prototype and heading as bool Function body must contain return statement(s) that return true or false Function body must contain return statement(s) that return true or false Calling function can use return value in a relational expression Calling function can use return value in a relational expression

Boolean return Example bool validTest(int); // prototype bool validTest(int test) // header { int lScore = 0, hScore = 100; if (test >= lScore && test = lScore && test <= hScore) return true; else return false; } if (validTest(score)) {...} // call

Passing Data by Value Pass by value: when an argument is passed to a function, its value is copied into the parameter. Pass by value: when an argument is passed to a function, its value is copied into the parameter. Changes to the parameter in the function do not affect the value of the argument Changes to the parameter in the function do not affect the value of the argument

Passing Information to Parameters by Value Example: int val=5; Example: int val=5; evenOrOdd(val); evenOrOdd(val); evenOrOdd can change variable num, but it will have no effect on variable val evenOrOdd can change variable num, but it will have no effect on variable val 5 val argument in calling function 5 num parameter in evenOrOdd function

Example #include #include using namespace std; //function declarations void changeThem(int,double); int main() { int whole=12; double real=3.5; cout << “the value of whole is ” << whole <<“\n”; << whole <<“\n”; cout << “the value of real is ” << real <<“\n”; << real <<“\n”; changeThem ( whole, real); cout << “Now, the value of whole is ” << whole <<“\n”; << whole <<“\n”; cout << “the value of real is ” << real <<“\n”; << real <<“\n”; return 0; } //Definition of function changeThem //it uses I, an int parameter, and f, a // double, the values of i and f are // changed and displayed. void changeThem(int i, double f) {i=100;f=24.5; cout << “value of i is changed to” << i <<“\n”; << i <<“\n”; cout << “value of f is changed to” << f <<“\n”; << f <<“\n”;}

Using Reference Variables as Parameters Mechanism that allows a function to work with the original argument from the function call, not a copy of the argument Mechanism that allows a function to work with the original argument from the function call, not a copy of the argument Allows the function to modify values stored in the calling environment Allows the function to modify values stored in the calling environment Provides a way for the function to ‘return’ > 1 value Provides a way for the function to ‘return’ > 1 value

Passing by Reference A reference variable is an alias for another variable A reference variable is an alias for another variable Defined with an ampersand ( & ) Defined with an ampersand ( & ) void getDimensions(int&, int&); Changes to a reference variable are made to the variable it refers to Changes to a reference variable are made to the variable it refers to Use reference variables to implement passing parameters by reference Use reference variables to implement passing parameters by reference

Example #include #include using namespace std; //function declarations void changeThem(int &,double &); int main() { int whole=12; double real=3.5; cout << “the value of whole is ” << whole <<“\n”; << whole <<“\n”; cout << “the value of real is ” << real <<“\n”; << real <<“\n”; changeThem ( whole, real); cout << “Now, the value of whole is ” << whole <<“\n”; << whole <<“\n”; cout << “the value of real is ” << real <<“\n”; << real <<“\n”; return 0; } //Definition of function changeThem //it uses I, an int parameter, and f, a // double, the values of i and f are // changed and displayed. void changeThem(int &i, double &f) {i=100;f=24.5; cout << “value of i is changed to” << i <<“\n”; << i <<“\n”; cout << “value of f is changed to” << f <<“\n”; << f <<“\n”;}

Pass by Reference - Example void sqareIt(int &); //prototype void squareIt(int &num) { num *= num; } int localVar = 5; squareIt(localVar); // now has 25

Reference Variable Notes Each reference parameter must contain & Each reference parameter must contain & Space between type and & is unimportant Space between type and & is unimportant Must use & in both prototype and header Must use & in both prototype and header Argument passed to reference parameter must be a variable – cannot be an expression or constant Argument passed to reference parameter must be a variable – cannot be an expression or constant Use when appropriate – don’t use when argument should not be changed by function, or if function needs to return only 1 value Use when appropriate – don’t use when argument should not be changed by function, or if function needs to return only 1 value

Using Functions in Menu-Driven Programs Functions can be used Functions can be used –to implement user choices from menu –to implement general-purpose tasks: Higher-level functions can call general- purpose functions, minimizing the total number of functions and speeding program development time Higher-level functions can call general- purpose functions, minimizing the total number of functions and speeding program development time

Default Arguments Default argument is passed automatically to a function if argument is missing on the function call Must be a constant declared in prototype: Must be a constant declared in prototype: void evenOrOdd(int = 0); Can be declared in header if no prototype Can be declared in header if no prototype Multi-parameter functions may have default arguments for some or all of them: Multi-parameter functions may have default arguments for some or all of them: int getSum(int, int=0, int=0);

Default arguments void showArea (double = 20.0, double = 10.0); void showArea (double = 20.0, double = 10.0); void showArea (double length= 20.0, double width= 10.0); void showArea (double length= 20.0, double width= 10.0); void showArea (double length, double width) { double area=length*width; cout << “The area is ” <<area << endl; }

Default arguments void showArea (double length = 20.0, double width = 10.0) { double area=length*width; cout << “The area is ” <<area << endl; }

Example #include #include using namespace std; //function declarations void displayStars(int =10, int = 1); int main() {displayStar();cout<<endl;displayStar(5);cout<<endl;displayStar(7,3); return 0; } //Definition of function displayStar. //the default argument for cols is 10 and // for rows is 1, this function displays a // square made of asterisks void displayStars(int cols, int rows); { for (int i=0, i < rows; i++) { for (int j=0, j < cols; j++) count << “*”; count << endl; }}

Default arguments If not all parameters to a function have default values, the defaultless ones are declared first in the parameter list: If not all parameters to a function have default values, the defaultless ones are declared first in the parameter list: int getSum(int, int=0, int=0); int getSum(int num1, int num2,int num3) { int sum; sum = num1+num2+num3; cout << “the sum of three number is ”<<sum<<endl; return sum; } int getSum(int, int=0, int);// int getSum(int=0, int, int);//

Local variable vs. Global Varialbe The general structure of a program: The general structure of a program:... Type 1 function 1 (…) {…} {…}... Type n function n (…) {…} {…} int main () {…} {…}

Example #include #include using namespace std; void anotherFunction(); int main() { int num=1; cout<<"in main, num is "<<num<<endl; anotherFunction(); cout<<"back in main, num is "<<num<<endl; return 0; } void anotherFunction() { int num=20; cout<<"in anotherFunction, num is "<<num<<endl; }

Local and Global Variables local variable: defined within a function or block, accessible only within the function or block local variable: defined within a function or block, accessible only within the function or block Other functions and blocks can define variables with the same name Other functions and blocks can define variables with the same name When a function is called, local variables in the calling function are not accessible from within the called function When a function is called, local variables in the calling function are not accessible from within the called function

Local and Global Variables global variable: defined outside all functions, accessible to all functions within its scope global variable: defined outside all functions, accessible to all functions within its scope Easy way to share large amounts of data between functions Easy way to share large amounts of data between functions Scope of a global variable: program from point of definition to the end Scope of a global variable: program from point of definition to the end Use sparingly Use sparingly

Example #include #include using namespace std; void anotherFunction(); int num=1; int main() { cout<<"in main, num is "<<num<<endl; anotherFunction(); num=70; num=70; cout<<"back in main, num is "<<num<<endl; return 0; } void anotherFunction() { cout<<"in anotherFunction, num is "<<num<<endl; cout<<"in anotherFunction, num is "<<num<<endl;num=20; cout<<"in anotherFunction, num is "<<num<<endl; }

Initializing Local and Global Variables Local variables must be initialized by programmer Local variables must be initialized by programmer Global variables are initialized to 0 (numeric) or NULL (character) when variable is defined Global variables are initialized to 0 (numeric) or NULL (character) when variable is defined

Local and Global Variable Names Local variables can have same names as global variables Local variables can have same names as global variables When a function contains a local variable that has the same name as a global variable, the global variable is unavailable from within the function. The local definition “hides” the global definition When a function contains a local variable that has the same name as a global variable, the global variable is unavailable from within the function. The local definition “hides” the global definition

#include #include using namespace std; void springfield(); void QinDao(); int students=20000; int main() { cout<<“there are "<<students<<“ students”<<endl; springfield(); void QinDao(); void QinDao(); cout<<"back in main, students "<<students<<endl; return 0; } void springfield() { int students=19000; int students=19000; cout<<"in springfield, "<<students<<endl; cout<<"in springfield, "<<students<<endl;} void QinDao() { int students=1000; int students=1000; cout<<"in QinDao, "<<students<<endl; cout<<"in QinDao, "<<students<<endl;}

Static Local Variables Local variables only exist while function is executing. When function terminates, contents of local variables are lost Local variables only exist while function is executing. When function terminates, contents of local variables are lost static local variables retain their contents between function calls static local variables retain their contents between function calls static local variables are defined and initialized only the first time the function is executed. 0 is default initialization static local variables are defined and initialized only the first time the function is executed. 0 is default initialization

Overloading Functions Overloaded functions have the same name but different parameter lists Overloaded functions have the same name but different parameter lists Can be used to create functions that perform the same task but take different parameter types or different number of parameters Can be used to create functions that perform the same task but take different parameter types or different number of parameters Compiler will determine which version of function to call by argument and parameter lists Compiler will determine which version of function to call by argument and parameter lists

Example #include #include using namespace std; //function declarations int square(int); double square(double); int main() { int userInt; double userDouble; cout << “Enter an integer and a double ” <<endl; <<endl;cin>>userInt>>userDouble; cout<<“Here are their squares: ” cout << square(userInt) <<“ and ” << square(userDouble); << square(userDouble); return 0; } int square(int number) { return number * number; } double square(double number) { return number * number; }

Function Overloading Examples Using these overloaded functions, void getDimensions(int); // 1 void getDimensions(int, int); // 2 void getDimensions(int, double); // 3 void getDimensions(double, double);// 4 the compiler will use them as follows: int length, width; double base, height; getDimensions(length); // 1 getDimensions(length, width); // 2 getDimensions(length, height); // 3 getDimensions(height, base); // 4

The exit() Function Terminates execution of a program Terminates execution of a program Can be called from any function Can be called from any function Can pass an int value to operating system to indicate status of program termination Can pass an int value to operating system to indicate status of program termination Usually used for abnormal termination of program Usually used for abnormal termination of program Requires cstdlib header file Requires cstdlib header file

Stubs and Drivers Stub: dummy function in place of actual function Stub: dummy function in place of actual function Usually displays a message indicating it was called. May also display parameters Usually displays a message indicating it was called. May also display parameters Driver: a program that tests a function by simply calling it Driver: a program that tests a function by simply calling it Useful for testing and debugging program and function logic and design Useful for testing and debugging program and function logic and design