Functions Chapter No. 5.

Slides:



Advertisements
Similar presentations
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
Advertisements

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.
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.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Overview of Previous Lesson(s) Over View  C++  KeywordsReserved words  IdentifiersProgrammers defined variables  Variables A named storage location.
1 Chapter 9 Scope, Lifetime, and More on Functions.
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.
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.
Object Oriented Programming Spring COMSATS Institute of Information Technology Functions OOP in C++ by Robert Lafore - Chapter#5 Kaleem Ullah
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapters 1-5 Review C++ Class. Chapter 1 – the big picture Objects Class Inheritance Reusability Polymorphism and Overloading.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 13 Thanks for lecture slides: Prentice Hall, Inc., 2. C++
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.
#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.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
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.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
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.
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.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Functions BICSE-6A Mr. Naeem Khalid Lecturer, Dept. of Computing.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Programming Languages -2 C++ Lecture 3 Method Passing Function Recursion Function Overloading Global and Local variables.
Programming Fundamentals Enumerations and Functions.
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.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
Functions  Simple Functions  Passing Arguments to Functions  Returning Values from Functions  Reference Arguments  Overloaded Functions  Recursion.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Functions.
User-Written Functions
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Chapter 1.2 Introduction to C++ Programming
Functions and an Introduction to Recursion
School of EECS, Peking University
Chapter 5 Functions.
Chapter 5 Conclusion CIS 61.
Student Book An Introduction
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
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
Pointers, Dynamic Data, and Reference Types
Functions.
6 Chapter Functions.
Dr. Khizar Hayat Associate Prof. of Computer Science
The Function Prototype
Functions and an Introduction to Recursion
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Functions Imran Rashid CTO at ManiWeber Technologies.
Dr. Khizar Hayat Associate Prof. of Computer Science
Standard Version of Starting Out with C++, 4th Edition
Corresponds with Chapter 5
Presentation transcript:

Functions Chapter No. 5

Contents Simple functions Passing arguments to functions Reference arguments Default arguments const Function arguments Returning values from functions Overloaded functions Inline functions Recursion Scope and storage classes Returning by reference

Simple functions A function groups a number of program statements into a unit and gives it a name Conceptual organization of a program Reduce the program size A function is made when same work in a program is repeated for more than one time Function’s code is stored in only one place in memory

Function Components Component Purpose Example Declaration Specifies function name, argument type and return value. Alerts compiler (or programmer) that a function is coming up later Void func(); Call Causes the function to be executed Func() Definition The function itself. Contains the lines of code that constitute the function Void func() { //lines of code } Declarator First line of definition

Example #include<iostream.h> void starline (); Int main() { starline(); cout<<“Data type Range”<<endl; cout<<“char -128 to 127”<<endl; cout<<“short -32,768 to 32,767”<<endl; cout<<“int -2,147,483,648 to 2,147,483,6487”<<endl; return 0; } //----------------------------------------------------- void starline() for(int i=0; i<45; i++) cout<<‘*’; cout<<endl;

Passing arguments to function An argument is a piece of data, e.g. int value, passed from a program to the function Passing constants starline(char , int); //function declaration: must mention type of arguments to be passed later starline(‘=’, 45) //call to function ‘=’ and 45 passed as constant arguments starline(char ch, int n) // function declarator (variables hold the argument values are called parameters) { // function body for(int i=0; i<n;i++) cout<<ch; cout<<endl; }

Passing variables- by value void repchar(char, int); int main() { Char chin; Int nin; Cout<<“Enter a character: ”; cin>> chin; Cout<<“Enter number to time to repeat it: ”; cin>>nin; repchar(chin, nin); return 0; } //-------------------- void repchar(char ch, int n) for(int i= 0; i<n; i++) cout<<ch; repchar(chin, nin); in main() causes the values in these variables to be copied into parameters in repchar(ch, n)

Structure as arguments Struct Distance{ int feet; float inches}; // structure declaration Void engldisp(Distance); // function declaration //----------------------------------- Int main() { Distance d1; Cout<<“Enter feet”; cin>>d1.feet; Cout<<“Enter inches”; cin>>d1.inches; engldisp(d1); // function call return 0; } //-------------------------------------- Void engldisp(Distance dd) cout<<dd.feet<<“------”<<dd.inches;

Reference arguments A reference is an alias – different name – for a variable Instead a value is being passed to the function, a reference (memory address) to the original variable, in the calling program, is passed Reference arguments are indicated by the ampersand (&) sign following the data type e.g. float& intp The & indicates that intp is an alias – another name – for whatever variable is passed as an argument

Cont’d main() { int i = 10, j = 20; swapThemByVal(i, j); cout << i << " " << j << endl; // displays 10 20 swapThemByRef(i, j); cout << i << " " << j << endl; // displays 20 10 ... } void swapThemByVal(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; } void swapThemByRef(int& num1, int& num2)

Difference between pass by value and pass by reference swapThemByVal() at start swapThemByVal() after assignment Main() temp …. num1 10 num2 20 temp 10 num1 20 num2 i 10 j 20 temp …. num1 --- num2 swapThemByRef() i 10 j 20 temp 10 num1 --- num2 swapThemByRef(): After assignment i 20 j 10 Difference between pass by value and pass by reference

Default arguments A function can be called without specifying all its arguments It can be done when declaration must provide default values for those arguments Default arguments are useful when arguments have always same values Example Void repchar( char =‘*’, int = 45)// declaration with default args. ///////---call in main()---- Repchar(); Repchar(‘=’); Repchar(‘+’,30);

const Function Arguments Passing arguments by reference can modify a variable in calling program When you want to pass an argument by reference but not want to modify a variable, const modifier is used for this purpose A variable already defined as const in the calling program must be passed as const argument

Example Void aFunction(int&, const int& b); Int main() { Int alpha = 7; Int beta = 11; aFunction(alpha, beta); return 0; } Void aFunction(int& a, const int& b) a = 107; //OK b = 111; //error: can’t modify constant argument

Returning values from functions When a function completes its execution it can return a single value to the calling program A return is actually a answer to the problem that function has solved When a function returns a value the data type must be specified Data type is mentioned in function declaration part return statement is use to return value Multiple values can be returned using reference arguments and other is return a structure

Example int add(int a,int b); int main() { int num1,num2,result; cout << " Enter number1: " << num1<< endl; cin>>num1; cout<<“Enter number 2: ”<<endl; cin>>num2; result = add(num1,num2); cout << " The result is : " << result << endl; return 0; } int add(int a, int b) int add; add = a + b; return add; }

Overloaded Functions In C++ two different functions can have the same name if their parameter types or number are different Compiler decides which function to call, depends on number of parameters or types int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/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); return 0; } Output 10 2.5

Inline functions Single copy of function is placed in memory Multiple calls are made from main program causes multiple jumps in memory which takes extra time for execution Inline function suggests compiler to place function code at each point the function is called The format for its declaration is: inline type name ( arguments ... ) { instructions ... }

Recursion Recursion involves a function calling itself long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } int main () long number; cout << "Please type a number: "; cin >> number; cout << “Factorial of ”<< number<<“is ”<< factorial (number); return 0;

Scope and Storage class Scope of a variable determines which part of program can access it. Two kinds Variables with local scope are visible only within block Variables with file scope are visible throughout a file Storage class determines how long it stays in existence Automatic: exist during lifetime of the function in which they are defined static : exist for the lifetime of the program

Cont’d Local Static local global Visibility Function File Lifetime Program program Initialized value Not initialized Storage Stack Heap Purpose Variables used by a single function Same as local, but retains value when function terminates Variables used by several functions

Returning by Reference Function that returns a reference is treated as if it were a variable. It returns alias to a variable There are two corollaries to this Can’t return a constant in setx() Can’t return a reference to local variable int x; int& setx() { return x; } int main() setx()=98; cout << "X: " << x<< endl; return 0;