Computer Programming 1 More on functions. Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value.

Slides:



Advertisements
Similar presentations
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
Advertisements

Chapter 7: User-Defined Functions II
Procedures and Control Flow CS351 – Programming Paradigms.
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
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.
 2006 Pearson Education, Inc. All rights reserved Functions.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.
 2007 Pearson Education, Inc. All rights reserved C Functions.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
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.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
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.
Chapter 6: User-Defined Functions
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Learners Support Publications Functions in C++
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 13 Thanks for lecture slides: Prentice Hall, Inc., 2. C++
Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference.
1 Functions  A function is a named, independent section of C++ code that performs a specific task and optionally returns a value to the calling program.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
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.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 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.
C++ Functions A bit of review (things we’ve covered so far)
Function Parameters and Overloading Version 1.0. Topics Call-by-value Call-by-reference Call-by-address Constant parameters Function overloading Default.
User-Written Functions
Data Type and Function Prepared for CSB210 Pemrograman Berorientasi Objek By Indriani Noor Hapsari, ST, MT Source: study.
C Functions -Continue…-.
Suppose we want to print out the word MISSISSIPPI in big letters.
FUNCTIONS In C++.
Methods Chapter 6.
Functions and an Introduction to Recursion
School of EECS, Peking University
Chapter 5 Functions.
Programmazione I a.a. 2017/2018.
Templates.
Chapter 5 - Functions Outline 5.1 Introduction
Group Status Project Status.
Object-Oriented Programming Using C++ Second Edition
Functions and an Introduction to Recursion
Functions Chapter No. 5.
Presentation transcript:

Computer Programming 1 More on functions

Computer Programming 2 Objectives Function overloading Scope rules and namespace Inline Templates Pass by value and pass by reference Recursion

Computer Programming 3 Scope What is wrong with the following piece of code? int n; n++; double n; Although the two function have parameters with same name, they compiler will not complain about re-declaring n twice! int sum (int n) { return n * (n + 1) / 2; } int sum (int m, int n){ assert ( m < n) ; return (n – m + 1) * (n + m) / 2; }

Computer Programming 4 Scope, scope rules The scope of an identifier is the portion of the program where it can be accessed. The scope rules are: 1. If an identifier is declared within a block, its scope runs from that point to end of block 2. If an identifier is a function parameter, its scope is the body of the function 3. If an identifier is declared in the initialization of a for loop, its scope is to the end of the loop 4. If an identifier's scope is declared outside all blocks and it is not a parameter, then it scope runs from that point to the end of the file

Computer Programming 5 Namespaces To be able to re-use declarations, namespace can be used Declarations can be placed within a namespace block namespace belNS { int value; //other declarations, definitions … } namespace mohNS { int value; } Elements within the namespace can be accessed – By using the fully qualified name belNS::value – mohNS::value – By its unqualified name (if no conflict), value, if using using namespace belNS::value; or sing namespace belNS;

Computer Programming 6 Function Overloading Can we have two functions with the same name and at the same time hold to the rule about no redeclaration of identifiers? The function signatures were different – Different numbers of parameters – Different types of parameters When this occurs we say the function name has been "overloaded" int sum (int n); int sum (int m, int n); int sum(double n);

Computer Programming 7 Inline Functions When one function calls another void f( int n ){... x = g(n);... } the process takes time for the program to transfer to a different location within the machine code With inline, it is possible to avoid the overhead required by this transfer

Computer Programming 8 Inline Functions Use the inline specifier in the prototype and definition inline double fahrToCelsius (double temp);... inline double fahrToCelsius (double temp){ return (temp – 32.0)/1.8; } The compiler now places actual code for the function in each location it is called – There is no jump to one location for the code at run time – This is very useful when a function with small code is called several times Inline functions are a trade-off – Faster execution at run time … but … – Larger.exe file Note that the compiler has the choice to inline a function or not Sometimes, a compiler may inline a function although the inline keyword is used

Computer Programming 9 Pass by value and Pass by reference So far, we have dealt with pass by value: only the value of the arguments are passed to the parameters double x = 212.0; change (x); //what’s the value of x? How can we change the value of x after change ? – Changing a value parameter changes the copy not its corresponding argument. Consider the task to divide two integers – We compute both the quotient and the remainder – We desire a function which returns both values, but we can only return value. What can we use to solve this? void change (double t) { t = 10.0; }

Computer Programming 10 Pass by reference Reference parameters – Parameters declared with an ampersand (&) – Following the parameter’s type (and before its name). A reference parameter is an alias to its corresponding argument. – Acts like another name for actual parameter Changing the value of a reference parameter changes the value of its corresponding argument.

Computer Programming 11 Pass by reference Function stub with reference parameters: void divideInts (int op1, int op2, int &quotient, int &remainder) { … } quotient and remainder are passed by reference. So, the values they have when divideInts returns are the values that the arguments will receive when its called. int i = 10,j=3; int quot=0,rem=0; divideInts(i,j,quot,rem); //the values of q and r becomes 3 and 1

Computer Programming 12 Passing values to parameters Value parameter – A distinct variable containing a copy of its argument – In previous example, op1 and op2 are value parameters

Computer Programming 13 Pass by reference Reference parameter – An alias of (alternate name for) the corresponding argument in the call – Changes to value of reference parameter will change the value of the corresponding argument in the call 1 2

Computer Programming 14 Pass by reference When the parameters are large then it is wise to use references Passing large arguments by valuing can be very expensive – Copying the value of the argument is very expensive when it is large – To avoid changing the value a parameter the use of the keyword const is very important int length(const string& s){ return s.length(); }

Computer Programming 15 Function template Consider the following swap function void swap(char& first, char& second){ char temporary = first; first = second; second = temporary; } Suppose we want to swap int s, doubles, strings, etc.. Are we going to write this function for every type? – This is were function templates come in!

Computer Programming 16 Function Templates Templates provide a pattern for the compiler to generate functions for whatever type of parameters are used in the call template void swap(Type &a, Type &b){ Type tmp = a; a = b; b = tmp; }

Computer Programming 17 Recursion Consider a function to calculate n-factorial – From mathematics – It can be defined recursively as follows

Computer Programming 18 Recursion A recursive definition must have two parts 1. A base/default case (s) The value is specified for one or more values of the parameter(s) 2. An inductive/recursive step The value for the parameter is specified in terms of previously defined value(s) and/or parameters

Computer Programming 19 Recursion To calculate 5! we go through the following steps:

Computer Programming 20 Recursion Then we backtrack

Computer Programming 21 Recursive Function The recursive factorial function int factorial (int n){ assert (n >= 0); if (n == 0) return 1; else return n * factorial (n – 1); }

Computer Programming 22 Execution of Recursive Function Observe the sequence of recursive calls when int number = factorial(4); Successive recursive calls

Computer Programming 23 Execution of Recursive Function When factorial(n - 1) eventually sends a 0 as the value parameter, the base case is executed – No more recursive calls...

Computer Programming 24 Execution of Recursive Function Now the calculated values are returned

Computer Programming 25 Numerical Methods Mathematical models used to solve practical problems Computer programs are used to manipulate such equations – Called "numerical methods" Examples – Curve fitting – Equation solving – Differential equations – Solving linear systems – Integration

Computer Programming 26 Numerical Methods Example Approximating the area under a curve Numerical methods approach – Divide region into strips, sum the areas – Trapezoidal method

Computer Programming 27 Function pointers Consider the problem described in the previous slide: – Compute the area under a function  – If the function  is known in advance, then it is easy to do. But suppose we want our program to take any function, how should we proceed? Use function pointers

Computer Programming 28 Function pointers Function pointers allow us to treat functions as if they are one of the basic types typedef double (*Fx)(double); double integral(double a, double b, Fx f) { double sum = 0.0,x; int n; // Evaluate integral{a,b} f(x) dx for (n = 0; n <= 100; n++) { x = (n/100.0)*(b-a) + a; sum += (*f)(x) * (b-a)/101.0; //you can f instead of (*f) } return sum; } double square(double x){ return x*x; } double third(double x){ return x*x*x; } … integral(0.0,1.0,square); integral(0.0,1.0,third);