Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Spring Semester 2013 Lecture 5
AU/MITM/1.6 By Mohammed A. Saleh 1. Arguments passed by reference  Until now, in all the functions we have seen, the arguments passed to the functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
CHAPTER:09 METHODS(FUNCTIONS) IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Introduction to C Programming
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
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 3 Getting Started with C++
C++ for Engineers and Scientists Third Edition
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
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.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
C++ Function 1. Function allow to structure programs in segment of code to perform individual tasks. In C++, a function is a group of statements that.
LECTURE 11 TYPES OF USER DEFINE FUNCTIONS ITC-414.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
Learners Support Publications Classes and Objects.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
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.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
Chapter 10 Introduction to Classes
Functions CIS Feb-06. Summary Slide Using Functions Mathematical Functions Misc. Functions Naming Conventions Writing Functions –Function Prototype.
Chapter 7 Functions CS185/09 - Introduction to Programming Caldwell College.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Chapter 6 Functions 6.1 Modular Design A valuable strategy when writing complex programs is to break down the program into several smaller modules. A module.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++ 16 September 2008.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
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.
 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.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
User-Written Functions
Data Type and Function Prepared for CSB210 Pemrograman Berorientasi Objek By Indriani Noor Hapsari, ST, MT Source: study.
School of EECS, Peking University
Chapter 5 Classes.
Introduction to Functions
Chapter 4 void Functions
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Chapter 6: User-Defined Functions I
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Functions Imran Rashid CTO at ManiWeber Technologies.
Functions Chapter No. 5.
Presentation transcript:

Functions Skill Area 314 Part B

Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters Overloaded Functions Passing by Value Passing by Reference Inline Functions Recursion

What is a FUNCTION? A function is a group of statements that is executed when it is called from some point of the program.

FUNCTION PROTOTYPE FUNCTION DEFINITION

Declaration and Definition Using functions in your program requires that you first declare the function and that you then define the function. The declaration tells the compiler the name, return type, and parameters of the function. The definition tells the compiler how the function works. No function can be called from any other function that hasn't first been declared. The declaration of a function is called its PROTOTYPE.

Function Prototype Many of the built-in functions you use will have their function prototypes already written in the files you include in your program by using #include. For functions you write yourself, you must include the prototype. The function prototype is a statement, which means it ends with a semicolon. It consists of the function's return type, name, and parameter list. The parameter list is a list of all the parameters and their types, separated by commas. int findArea (int length, int width); return type name parameters Parameter type Parameter name semicolon

Prototype that looks like this is perfectly legal (without parameter name): int findArea (int, int); Function Prototype Although this is legal, it is not a good idea. Adding parameter names makes your prototype clearer. The same function with named parameters might be int findArea (int height, int width);

Function Definition The definition of a function consists of the function header and its body. The header is exactly like the function prototype, except that the parameters must be named, and there is no terminating semicolon. The body of the function is a set of statements enclosed in braces return_type function_name ( [type parameterName]...) { statements; } int area ( int height, int width) { return height* width; }

Function Definition return type is the data type specifier of the data returned by the function. function_name is the identifier by which it will be possible to call the function. parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas. statements is the function's body. It is a block of statements surrounded by braces { }. return_type function_name ( [type parameterName]...) { statements; }

NOTE The function prototype and the function definition must agree exactly about the return type, the name, and the parameter list. If they do not agree, you will get a compile-time error.

Functions #include using namespace std; int add (int a, int b); //function prototype int main () { int x=1, y=3; cout << "x + y= "<< add(x,y); //calling function add() system ("pause"); return 0; } //function definition int add (int a, int b) { return a+b; } #include using namespace std; int add (int a, int b); //function prototype int main () { int x=1, y=3; cout << "x + y= "<< add(x,y); //calling function add() system ("pause"); return 0; } //function definition int add (int a, int b) { return a+b; }

NOTE If you try to placing the a function before the main() function without declared the function first, you will have compile-time error

Functions with no Type (VOID) We do not need it to return any value. We use the void type specifier for the function. This is a special specifier that indicates absence of type. It is called PROCEDURE //function definition void printmessage () { cout << “I’m a function!”; } void printmessage() ; //function prototype

Functions with no Type (VOID) // void function example #include using namespace std; void printmessage (); //function prototype int main () { printmessage (); return 0; } //function definition void printmessage () { cout << "I'm a function!"; } // void function example #include using namespace std; void printmessage (); //function prototype int main () { printmessage (); return 0; } //function definition void printmessage () { cout << "I'm a function!"; }

Functions with no Type (VOID) // void function example #include using namespace std; void subtract(int a, int b); //function prototype int main () { int x=7, y=2; subtract (x,y); return 0; } //function definition void subtract(int a, int b) { int c; c=a-b; cout << c; } // void function example #include using namespace std; void subtract(int a, int b); //function prototype int main () { int x=7, y=2; subtract (x,y); return 0; } //function definition void subtract(int a, int b) { int c; c=a-b; cout << c; }

LOCAL VARIABLES GLOBAL VARIABLES

Scope of Variables The scope of variables declared within a function or any other inner block is only their own function or their own block and cannot be used outside of them. Local variables are defined like any other variables. The parameters passed in to the function are also considered local variables and can be used exactly as if they had been defined within the body of the function. Variables defined outside of any function have global scope and thus are available from any function in the program, including main(). In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program.

Scope of Variables #include using namespace std; int multiply (int a, int b); int x=5, y=6; //GLOBAL variables int main() { int i=7,j=9; //LOCAL variables cout << multiply(i,j) << endl; cout<< multiply(x,y); return 0; } int multiply (int a, int b) { int z; //LOCAL variables z=a*b; return z; } #include using namespace std; int multiply (int a, int b); int x=5, y=6; //GLOBAL variables int main() { int i=7,j=9; //LOCAL variables cout << multiply(i,j) << endl; cout<< multiply(x,y); return 0; } int multiply (int a, int b) { int z; //LOCAL variables z=a*b; return z; }

DEFAULT PARAMETERS

DEFAULT Parameters When declaring a function we can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead.

DEFAULT Parameters For every parameter you declare in a function prototype and definition, the calling function must pass in a value. The value passed in must be of the declared type. A default value is a value to use if none is supplied int findArea (int height, int width); int findArea (int height = 50, int width=75);

DEFAULT Parameters If the function prototype looks like You can assign a default value to Param2 only if you have assigned a default value to Param3. You can assign a default value to Param1 only if you've assigned default values to both Param2 and Param3 int myFunction (int Param1, int Param2, int Param3);

DEFAULT Parameter #include using namespace std; int divide (int a, int b=2); //function prototype int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; } //function definition int divide (int a, int b) { int r; r=a/b; return (r); } #include using namespace std; int divide (int a, int b=2); //function prototype int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; } //function definition int divide (int a, int b) { int r; r=a/b; return (r); }

DEFAULT Parameter #include using namespace std; int AreaCube(int length, int width = 25, int height = 1); int main() { int length = 100; int width = 50; int height = 2; int area; area = AreaCube(length, width, height); cout << "First area equals: " << area << "\n"; area = AreaCube(length, width); cout << "Second time area equals: " << area << "\n"; area = AreaCube(length); cout << "Third time area equals: " << area << "\n"; return 0; } AreaCube(int length, int width, int height) { return (length * width * height); } #include using namespace std; int AreaCube(int length, int width = 25, int height = 1); int main() { int length = 100; int width = 50; int height = 2; int area; area = AreaCube(length, width, height); cout << "First area equals: " << area << "\n"; area = AreaCube(length, width); cout << "Second time area equals: " << area << "\n"; area = AreaCube(length); cout << "Third time area equals: " << area << "\n"; return 0; } AreaCube(int length, int width, int height) { return (length * width * height); }

OVERLOADED FUNCTIONS

OVERLAODED Functions In C++ two different functions can have the same name if their parameter types or number are different. That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters. The functions must differ in their parameter list, with a different type of parameter, a different number of parameters, or both Function overloading is also called function polymorphism. Poly means many, and morph means form: a polymorphic function is many-formed.

OVERLOADED Functions #include using namespace std; int operate (int a, int b); float operate (float a, float b) int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; } int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); } #include using namespace std; int operate (int a, int b); float operate (float a, float b) int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0; } int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); }

ARGUMENTS PASSED BY VALUE AND BY REFERENCE

Passing by VALUE What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves. int x=5, y=3, z; z = addition ( x, y ); This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called.

Passing by REFERENCE There might be some cases where you need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference. The first thing that should call your attention is that in the declaration of function the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value. When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.

Passing by REFERENCE To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the same with c and z. That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled. Without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and z without having been modified. Passing by reference is also an effective way to allow a function to return more than one value

Passing by REFERENCE //with ampersand sign (&) #include using namespace std; void operate(int& a); int main () { int x=3; operate(x); cout << x; return 0; } void operate (int& a) { a=2; } Output: 2 //with ampersand sign (&) #include using namespace std; void operate(int& a); int main () { int x=3; operate(x); cout << x; return 0; } void operate (int& a) { a=2; } Output: 2 //without ampersand sign (&) #include using namespace std; void operate(int a); int main () { int x=3; operate(x); cout << x; return 0; } void operate (int a) { a=2; } Output: 3 //without ampersand sign (&) #include using namespace std; void operate(int a); int main () { int x=3; operate(x); cout << x; return 0; } void operate (int a) { a=2; } Output: 3

Passing by REFERENCE // more than one returning value #include using namespace std; void prevnext (int x, int& prev, int& next); int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; } void prevnext (int x, int& prev, int& next) { prev = x-1; next = x+1; } // more than one returning value #include using namespace std; void prevnext (int x, int& prev, int& next); int main () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; } void prevnext (int x, int& prev, int& next) { prev = x-1; next = x+1; }

INLINE FUNCTIONS

What is INLINE functions? The inline functions are a C++ enhancement designed to speed up programs. The coding of normal functions and inline functions is similar except that inline functions definitions start with the keyword inline. The distinction between normal functions and inline functions is the different compilation process.

Reason for the need of Inline Function Normally, a function call transfers the control from the calling program to the function and after the execution of the program returns the control back to the calling program after the function call. These concepts of function save program space and memory space and are used because the function is stored only in one place and is only executed when it is called. This execution may be time consuming since the registers and other processes must be saved before the function gets called. The extra time needed and the process of saving is valid for larger functions. If the function is short, the programmer may wish to place the code of the function in the calling program in order for it to be executed. This type of function is best handled by the inline function.

What happens when an inline function is written? The inline function takes the format as a normal function but when it is compiled it is compiled as inline code. The function is placed separately as inline function, thus adding readability to the source program. When the program is compiled, the code present in function body is replaced in the place of function call.

INLINE Functions The format for its declaration is: inline type name ( arguments... ) { instructions... }

INLINE Functions #include using namespace std; int exforsys(int); int main( ) { int x; cout << "n Enter the Input Value: "; cin>>x; cout << "n The Output is: " << exforsys(x); return 0; } inline int exforsys (int x1) //INLINE Function { return 5*x1; } #include using namespace std; int exforsys(int); int main( ) { int x; cout << "n Enter the Input Value: "; cin>>x; cout << "n The Output is: " << exforsys(x); return 0; } inline int exforsys (int x1) //INLINE Function { return 5*x1; }

RECURSION

A function can call itself. This is called recursion, and recursion can be direct or indirect. It is direct when a function calls itself; it is indirect recursion when a function calls another function that then calls the first function. It is useful for many tasks, like sorting or calculate the factorial of numbers.

RECURSION #include using namespace std; void CountDown(int nValue); int main() { CountDown(10); return 0; } void CountDown(int nValue) { cout << nValue << endl; // termination condition if (nValue > 0) CountDown(nValue-1); //RECURSION } #include using namespace std; void CountDown(int nValue); int main() { CountDown(10); return 0; } void CountDown(int nValue) { cout << nValue << endl; // termination condition if (nValue > 0) CountDown(nValue-1); //RECURSION }

--- continue to next slide ---