Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables.

Slides:



Advertisements
Similar presentations
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
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.
Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create.
Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create.
Function Overloading Can enables several functions Of same name Of different sets of parameters (at least as far as their types are concerned) Used to.
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.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Templates Overload function: define more than one function With same function name Different parameter type Different type Different number of parameter.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
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.
CS1201: Programming Language 2 Recursion By: Nouf Almunyif.
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.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Object Oriented Programming Spring COMSATS Institute of Information Technology Functions OOP in C++ by Robert Lafore - Chapter#5 Kaleem Ullah
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
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
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.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 13 Thanks for lecture slides: Prentice Hall, Inc., 2. C++
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
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.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Function Overloading and References
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
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.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Methods Awesomeness!!!. Methods Methods give a name to a section of code Methods give a name to a section of code Methods have a number of important uses.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
EC-111 Algorithms & Computing Lecture #6 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.
Functions BICSE-6A Mr. Naeem Khalid Lecturer, Dept. of Computing.
User-Defined Functions (cont’d) - Reference Parameters.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
CS1201: Programming Language 2 Function I By: Nouf Aljaffan Edited by : Nouf Almunyif.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
LECTURE 3 PASS BY REFERENCE. METHODS OF PASSING There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference, 
Functions.
User-Written Functions
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 7: User-Defined Functions II
CSC1201: Programming Language 2
School of EECS, Peking University
Chapter 5 Functions.
Function There are two types of Function User Defined Function
CS1201: Programming Language 2
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Return_DT F_name ( list of formal parameters)
FUNCTIONS& FUNCTIONS OVERLOADING
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.
Dr. Khizar Hayat Associate Prof. of Computer Science
CS1201: Programming Language 2
The Function Prototype
CS1201: Programming Language 2
CSC1201: Programming Language 2
Dr. Khizar Hayat Associate Prof. of Computer Science
CS1201: Programming Language 2
Intro to Programming Week # 8 Functions II Lecture # 13
Functions Chapter No. 5.
Presentation transcript:

Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables

Methods of Passing  There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference,  and pass by address. ( will be addressed later)

Methods of Passing  When passing arguments by value, the only way to return a value back to the caller is via the function’s return value.  While this is suitable in many cases, there are a few cases where better options are available.

Methods of Passing  When arguments are passed by value, the called function creates a new variable of the same type as the argument and copies the argument’s value into it. As we noted, the function cannot access the original variable in the calling program, only the copy it created.  Passing arguments by value is useful when the function does not need to modify the original variable in the calling program.  In fact, it offers insurance that the function cannot harm the original variable.

Passing Arguments by Reference  Passing arguments by reference uses a different mechanism. Instead of a value being passed to the function, a reference to the original variable, in the calling program, is passed.  An important advantage of passing by reference is that the function can access the actual variables in the calling program.  This provides a mechanism for passing more than one value from the function back to the calling program.

Passing Arguments by Reference  In pass by reference, we declare the function parameters as references rather than normal variables: #include Using namespace std ; Void duplicate (int& a, int& b, int & c); Int main () { Int x=1,y=3,z=7; Duplicate (x,y,z); Cout << “x=“<<x<<“, y=“<<y<<“,z=“<<z; Return 0; } Void duplicate (int& a, int& b, int & c) {a*=2; b*=2; c*=2; }

Passing Arguments by Reference Reference arguments are indicated by the ampersand (&) following the data type: int& a When the function is called, a will become a reference to the argument. Since a reference to a variable is treated exactly the same as the variable itself, then any changes made to the reference are passed through to the argument!

Passing Arguments by Reference  Sometimes we need a function to return multiple values.  However, functions can only have one return value.  One way to return multiple values is using reference parameters.

Advantages of passing by reference  It allows us to have the function change the value of the argument, which is sometimes useful.  Because a copy of the argument is not made, it is fast, even when used with large structs or classes.  We can pass by const reference to avoid unintentional changes.  We can return multiple values from a function.

Recursion and Recursive Functions  Main calls another function…..normal  A function calls another function2….normal  A function calls itself ?! Possible?? YES  A recursive function is one that call itself.

Recursion and Recursive Functions  An example to print numbers counting down: void print (int p) { if (p==0) return; cout<<p; print(p-1); return; }

Finding Factorial Recursively 5! 5*4! 4*3! 3*2! 2*1! 1 1 5! 5*4! 4*3! 3*2! 2*1! 1 1 Final value= !=2*1=2 returned 3!=3*2=6 returned 4!=4*6=24 returned 5!=5*24=120 returned

Finding Factorial Recursively //Recursive factorial Function #include unsigned long factorial(unsigned long);//prototype int main() { int num; cout<<“enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); return 0; } unsigned long factorial(unsigned long n) { if ( n <= 1) //the base case return 1; else return n * factorial (n - 1); } //Recursive factorial Function #include unsigned long factorial(unsigned long);//prototype int main() { int num; cout<<“enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); return 0; } unsigned long factorial(unsigned long n) { if ( n <= 1) //the base case return 1; else return n * factorial (n - 1); }

Function Overloading  Functions with same name and different parameters or return data type  Should perform similar tasks  I.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; }  A call-time c++ complier selects the proper function by examining the number, type and order of the parameters

Function Overloading  An overloaded function appears to perform different activities depending on the kind of data sent to it.  It performs one operation on one kind of data but another operation on a different kind.

Function Overloading #include Using namespace std; Void repchar();//declarations Void repchar(char); Void repchar(char, int); intmain() { repchar(); //First repchar(‘=’); //Second repchar(‘+’,30); //Third Return 0; }

Void repchar() // first { For (int j=0; j<45; j++) cout<<‘*’; cout<<endl; } Void repchar (char ch) // Second { For (int j=0;j<45; j++) cout<<ch; cout<<endl; } Void repchar(char ch,int n) //Third { for(int j=0;j<n; j++) cout<<ch; cout<<endl; }

Function Overloading This program prints out three lines of characters. Here’s the output: ********************************************* =============================================

Function Overloading  The program contains three functions with the same name.  There are three declarations, three function calls, and three function definitions.  The compiler uses the function signature—the number of arguments, and their data types—to distinguish one function from another.

Function Overloading  voidrepchar();  which takes no arguments, describes an entirely different function than the declaration  voidrepchar(char);  which takes one argument of type char, or the declaration  voidrepchar(char, int);  which takes one argument of type char and another of type int.

Global and Local Variables  A variable’s scope, also called visibility, describes the locations within a program from which it can be accessed.  The scope of a variable determines which parts of the program can access it.  Scope: Local and Global  Variables defined within a function body are called local variables because they have local scope. voidsomefunc() { int somevar;//variablesdefinedwithin float othervar;//thefunctionbody }

Global and Local Variables  Variables defined within a function are only visible, meaning they can only be accessed, from within the function in which they are defined. Void somefunc() { intsomevar;//localvariables float othervar; somevar=10;//OK othervar=11;//OK nextvar=12;//illegal:notvisibleinsomefunc() } void otherfunc() { intnextvar; //localvariable somevar=20;//illegal:notvisibleinotherfunc() othervar=21;//illegal:notvisibleinotherfunc() nextvar=22;//OK }

Global and Local Variables  A global variable is used when it must be accessible to more than one function in a program.  While local variables are defined within functions, global variables are defined outside of any function.  Global variable is visible to all those functions that follow the variable’s definition in the listing.

Global and Local Variables