CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.

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

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Chapter 7: User-Defined Methods
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: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Chapter 6: Functions.
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Chapter 06 (Part I) Functions and an Introduction to Recursion.
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.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan Snd Term Nouf Aljaffan (C) CSC 1201 Course at KSU1.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
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.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
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.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 12.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.
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.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
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.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 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 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
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 + Overloading + Scope
User-Written Functions
Chapter 7: User-Defined Functions II
CSC1201: Programming Language 2
Introduction to C++ Systems Programming.
FUNCTIONS IN C++.
Programmazione I a.a. 2017/2018.
User-Defined Functions
CSC1201: Programming Language 2
CS1201: Programming Language 2
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.
CS1201: Programming Language 2
CS1201: Programming Language 2
CSC1201: Programming Language 2
CSC1201: Programming Language 2
Functions Imran Rashid CTO at ManiWeber Technologies.
CS1201: Programming Language 2
Presentation transcript:

CSC1201: Programming Language 2 1 Functions

2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program can contain one or many functions Must always have a function called “main”. The main function is the starting point of all C++ programs The compiler will not compile the code unless it finds a function called “main” within the program. A program can contain one or many functions Must always have a function called “main”. The main function is the starting point of all C++ programs The compiler will not compile the code unless it finds a function called “main” within the program. A Function is a group of statements that together perform a task. It can be used anywhere in the program. Why we need function? – Organize code in program – Code are easier to maintain?

“Hello World” program 3 #include using namespace std; int main () ‏ { cout << “Hello World\n”; Return 0; }

Function 4 When we need function? – When you need to repeat the same process over and over in a program. – The function can be called many times but appears in the code once.

1- Predefined functions 5  Predefined functions are functions that are built into C++ Language to perform some standard operations.  The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings  the definitions have been written and it is ready to be used.  User needs to include pre-defined header file (i.e. math.h, time.h)

2- User defined functions 6  Function that been created by the user.  This functions need to be declared and defined by the user

functions 7  Value returning functions:  functions that have a return type.  These functions return a value of a specific data type using the return statement.  Void functions:  functions that do not have a return type.  These functions do not use a return statement to return a value.

Value returning functions 8 The syntax is: FuncType FuncName(formal parameter list )‏ { statements }

Void functions 9 The syntax is: Void FuncName ( formal parameter list )‏ { statements }

Examples: Write a Function larger, which returns the larger of the two given doubles. 2. Write a Function Square, which returns the square of the given integer. 3. Write a function number_type. The function should output the number and message saying whether the number is positive, negative, or zero.

Example: With return value 11 #include using namespace std; Double larger ( double x, double y )‏ { double max; if ( x >= y )‏ max = x; else max = y; return max; } int main ( )‏ { cout << “The larger of 5 and 6 is “ << larger(5, 6) << endl; //Function Call return 0; }

Example: With return value 12 #include using std::cin; using std::cout; using std::endl; int square (int x)‏ { return x*x; } int main ( )‏ { int number; cout<<"Enter any number to Calculate the square of this number "; cin>>number; cout<<endl; cout<<"the square of "<<number<<" is " <<square(number)<<endl; //Function Call return 0; }

Example: Without return value 13 #include using namespace std; void number_type ( int x) ‏ { if ( x > 0 ) ‏ cout << x << “ is positive.” << endl; else if ( x < 0 ) ‏ cout << x << “ is negative.” << endl; else cout<< x << “is a zero.”<<endl; } int main ( ) ‏ { number_type( 5 ); //Function Call return 0; }

Function reusable  The function are reusable. ProceduresRoutines Methods  Functions may be called Procedures or Routines and in object oriented programming called Methods.  Save programmers’ time. 14

Prototype VS. Declaration Prototype : n ormally placed before the start of main() but must be before the function definition. General form : function_return_type function_name (type parameter1, type parameter2,…, type parameterN) ; EX: void Factorial (int x); // prototype -- x is a parameter 15

Prototype VS. Declaration Prototype : void foo(int x); // prototype -- x is a parameter  Declaration  void foo(int x) // declaration -- x is a parameter { Statements. } 16

EX: #include using namespace std; int square (int x)‏ {return x*x;} void main ( )‏ { int number; cout<<"Enter any number to Calculate the square of this number "; cin>>number; cout<<endl; cout<<"the square of "<<number<<" is " <<square(number)<<endl; } 17

EX: #include using namespace std; int square (int x)‏ ; Void main ( )‏ { int number; cout<<"Enter any number to Calculate the square of this number "; cin>>number; cout<<endl; cout<<"the square of "<<number<<" is " <<square(number)<<endl; } int square (int x)‏ {return x*x;} 18

Finding Errors in Function Code int sum(int x, int y) { int result; result = x+y; }  this function must return an integer value as indicated in the header definition (return result;) should be added  this function must return an integer value as indicated in the header definition (return result;) should be added 19

Finding Errors in Function Code int sum (int n) { if (n==0) return 0; else n+(n-1); }  the result of n+(n-1) is not returned; sum returns an improper result, the else part should be written as:- else return n+(n-1);  the result of n+(n-1) is not returned; sum returns an improper result, the else part should be written as:- else return n+(n-1); 20

Finding Errors in Function Code void f(float a); { float a; cout<<a<<endl; }  ; found after function definition header.  redefining the parameter a in the function void f(float a) { float a2 = a + 8.9; cout <<a2<<endl; }  ; found after function definition header.  redefining the parameter a in the function void f(float a) { float a2 = a + 8.9; cout <<a2<<endl; } 21

Finding Errors in Function Code void product(void) { int a, b, c, result; cout << “enter three integers:”; cin >> a >> b >> c; result = a*b*c; cout << “Result is” << result; return result; }  According to the definition it should not return a value, but in the block (body) it did & this is WRONG.  Remove return Result;  According to the definition it should not return a value, but in the block (body) it did & this is WRONG.  Remove return Result; 22

Scope of variables

C++ Variables  A variable is a place in memory that has  A name or identifier (e.g. income, taxes, etc.)  A data type (e.g. int, double, char, etc.)  A size (number of bytes)  A scope (the part of the program code that can use it)  Global variables – all functions can see it and using it  Local variables – only the function that declare local variables see and use these variables  A life time (the duration of its existence)  Global variables can live as long as the program is executed  Local variables are lived only when the functions that define these variables are executed 24

25

Global VS Local variables  local variable  Variables that declared inside a function  Declared inside any block of code  Global variables  Opposite of local the known throughout the entire program 26

Global VS Local variables #include Using namespace std; 27

Global VS Local variables #include Using namespace std; void main() { int i=4; int j=10; i++; if (j > 0) cout<<“ I is “<<i<<endl; if (j > 0) { int i=100; /* 'i' is defined and so local to * this block */ cout << “I is” << i; } //end if cout<<“I is “<<i; } //end main I is 5 I is 100 I is 5 28

Scope of Local Variables, cont. 29

Variable Scope  In fact, you can reuse names in a scope which is nested inside another scope int main ( ) { int i = 5, j = 0; for (j = 0; j < 10; j++) { int i = j;// OK, this is new i int k = 5; doSomething (i); } int sum = k; // compile error, no k in scope j = i; // sets j to 5 for (j = 0; j < 100; j++ ) { int i = j; // yet another new i } int i = 0; // compile error –redefined variable } void doSomething(int i){ cout<<++i ;}// OK, this is new i 30

Variable Scope  Local variables of same name can be nested inside global variables int total = 5; int main ( ) { int total = 4; // OK, this is nested scope …. } int sub1 ( ) { int i = total; // OK, i set to 5 } #include using namespace std; int i = 10; int main ( ) { cout<<i<<endl;//10 for (int j = 0; j < 10; j++ ) { int i = 20; cout<<i<<endl;//20 } cout<<i<<endl;//10 int i = 30; cout<<i<<endl;//30 return 0;} 31

I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 32

I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 0 33

I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 0 void main() { f2(); f2(); cout << x << endl ; cout << x << endl ;} 1 34

I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 0 void main() { f2(); f2(); cout << x << endl ; cout << x << endl ;} 1 void f2() { x += 4; x += 4; f1(); f1();}

45 I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x void main() { f2(); f2(); cout << x << endl ; cout << x << endl ;} 1 void f2() { x += 4; x += 4; f1(); f1();} 3 void f1() { x++; x++;} 4 36

45 I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 1 void f2() { x += 4; x += 4; f1(); f1();} 3 void f1() { x++; x++;} 5 37

45 I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 1 void f2() { x += 4; x += 4; f1(); f1();} 6 38

45 I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 7 39

45 I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x void main() { f2(); f2(); cout << x << endl; cout << x << endl;} 8 40

I. Using Global Variables #include using namespace std; int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 41

What is Bad About Using Global Vairables?  Not safe!  If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value!  Against The Principle of Information Hiding!  Exposing the global variables to all functions is against the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!) 42

Local Variables  Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit  You have to initialize the local variable before using it  If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable 43

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } 44

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 0 Global variables are automatically initialized to 0 45

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 0 void main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 1 46

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x ???? 3 47

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function signature Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 2 void fun() { int x = 10; int x = 10; cout << x << endl; cout << x << endl;} x

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 6 51

Example of Defining and Using Global and Local Variables #include using namespace std; // Global variable int x; // Global variable // function prototype Void fun(); // function prototype void main() { x = 4; fun(); cout << x << endl; } void fun() { // Local variable int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(); fun(); cout << x << endl; cout << x << endl;} 7 52

Example of Using Value Parameters and Global Variables #include using namespace std; // Global variable int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 0 void main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 1 53

Example of Using Value Parameters and Global Variables #include using namespace std; // Global variable int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 2 void fun(int x ) { cout << x << endl; cout << x << endl; x=x+5; x=x+5;}

Example of Using Value Parameters and Global Variables #include using namespace std; // Global variable int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 2 void fun(int x ) { cout << x << endl; cout << x << endl; x=x+5; x=x+5;}

Example of Using Value Parameters and Global Variables #include using namespace std; // Global variable int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 2 void fun(int x ) { cout << x << endl; cout << x << endl; x=x+5; x=x+5;}

Example of Using Value Parameters and Global Variables #include using namespace std; // Global variable int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 6 57

Example of Using Value Parameters and Global Variables #include using namespace std; // Global variable int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 4 void main() { x = 4; x = 4; fun(x/2+1); fun(x/2+1); cout << x << endl; cout << x << endl;} 7 58

Methods of Passing

 There are 2 primary methods of passing arguments to functions:  pass by value,  pass by reference, 60

Absolute value #include using namespace std; int absolute (int);// function prototype for absolute() int main(){ int num, answer; cout << "Enter an integer (0 to stop): "; cin >> num; while (num!=0){ answer = absolute(num); cout << "The absolute value of " << num << " is: " << answer << endl; cin >> num; } return 0; } // Define a function to take absolute value of an integer int absolute(int x){ if (x >= 0)return x; else return -x; } 61

Methods of Passing  There are 2 primary methods of passing arguments to functions:  pass by value,  pass by reference, 62

Passing arguments by reference  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. 63

Passing arguments by reference  In pass by reference, we declare the function parameters as references rather than normal variables: void AddOne(int & y) // y is a reference variable { y = y + 1; } When the function is called, y will become a reference to the argument. The reference to a variable is treated exactly the same as the variable itself. any changes made to the reference are passed through to the argument! 64

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 65

Cont. Example void foo(int &y) // y is now a reference { cout << "y = " << y << endl; y = 6; cout << "y = " << y << endl; } // y is destroyed here int main() { int x = 5; cout << "x = " << x << endl; foo(x); cout << "x = " << x << endl; return 0; }  This program is the same as the one we used for the pass by value example, except foo’s parameter is now a reference instead of a normal variable.  When we call foo(x), y becomes a reference to x.  Note that the value of x was changed by the function! 66

Passing arguments by reference Example 2 void AddOne(int &y) { y++; } int main() { int x = 1; cout << "x = " << x << endl; AddOne(x); cout << "x = " << x << endl; return 0; } 67

Passing arguments by reference Example 3 #include Using namespace std ; Void duplicate (int& a, int& b, int & c); Void main () { Int x=1,y=3,z=7; Duplicate (x,y,z); Cout << “x=“<<x<<“, y=“<<y<<“,z=“<<z; } Void duplicate (int& a, int& b, int & c) {a*=2; b*=2; c*=2; } 68

Passing arguments by reference Example 4 #include Using namespace std ; void swap(float &x, float &y); int main() { float a, b; cout << "Enter 2 numbers: " << endl; cin >> a >> b; if(a>b) swap(a,b); cout << "Sorted numbers: "; cout << a << " " << b << endl; return 0; } void swap(float &x, float &y) { float temp; temp = x; x = y; y = temp; } 69

Passing arguments by reference 1 #include #include // for sin() and cos() Using namespace std; void GetSinCos(double dX, double &dSin, double &dCos) { dSin = sin(dX); dCos = cos(dX); } int main() { double dSin = 0.0; double dCos = 0.0; GetSinCos(30.0, dSin, dCos); cout << "The sin is " << dSin << endl; cout << "The cos is " << dCos << endl; return 0; } 70

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 structus or classes.  We can pass by CONST reference to avoid unintentional changes.  We can return multiple values from a function. 71

Function Overloading

73 Function Overloading  Two or more functions can have the same name but different parameters  Example: int max(int a, int b) { if (a>= b) return a; else return b; } float max(float a, float b) { if (a>= b) return a; else return b; }

Function Overloading  In a C++ program, several functions can have the same name  This is called function overloading or overloading a function name 74

Function Overloading (continued)  Two functions are said to have different formal parameter lists if both functions have:  A different number of formal parameters, or  If the number of formal parameters is the same, then the data type of the formal parameters, in the order you list them, must differ in at least one position 75

The functions functionSix and functionSeven both have three formal parameters and the data type of the corresponding parameters is the same; therefore, these functions have the same formal parameter list 76

Function overloading: creating several functions with the same name The signature of a function consists of the function name and its formal parameter list Two functions have different signatures if they have either different names or different formal parameter lists Note that the signature of a function does not include the return type of the function Function Overloading (continued) 77

These function headings correctly overload the function functionXYZ : Both of these function headings have the same name and same formal parameter list Therefore, these function headings to overload the function functionABC are incorrect In this case, the compiler will generate a syntax error Note that the return types of these function headings are different 78

Functions with Default Parameters  When a function is called  The number of actual and formal parameters must be the same  C++ relaxes this condition for functions with default parameters  You specify the value of a default parameter when the function name appears for the first time, such as in the prototype 79

Functions with Default Parameters (continued)  If you do not specify the value of a default parameter  The default value is used  All of the default parameters must be the rightmost parameters of the function  In a function call where the function has more than one default parameter and a value to a default parameter is not specified  You must omit all of the arguments to its right 80

Functions with Default Parameters (continued)  Default values can be constants, global variables, or function calls  The caller has the option of specifying a value other than the default for any default parameter  You cannot assign a constant value as a default value to a reference parameter 81

82

83

Function Overloading  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 84

Function overloading Example 85 #include using namespace std; void FtoC(int temp); void FtoC(float temp); void FtoC(double temp); int main()‏ { int inttemp, level; float floattemp; double doubletemp; cout << "CONVERTING FAHRENHEIT TO CELSIUS\n"; cout << "Select required level of precision\n"; cout << "Integer (1) - Float (2) - Double (3)\n"; cin >> level; cout << "Enter Fahrenheit temperature: "; switch (level)‏ { case 1 :cin >> inttemp; FtoC(inttemp); break; case 2 : cin >> floattemp; FtoC(floattemp); break; case 3 : cin >> doubletemp; FtoC(doubletemp); break; default : cout << "Invalid selection\n"; } return 0; }

Function overloading Cont. 86 void FtoC( int itemp)‏ { int temp = (itemp - 32) * 5 / 9; cout << "Integer precision: "; cout << itemp << "F is " << temp << "C\n"; } void FtoC( float ftemp)‏ { float temp = (ftemp - 32) * 5.0 / 9.0; cout << "Float precision: "; cout << ftemp << "F is " << temp << "C\n";; } void FtoC( double dtemp)‏ { double temp = (dtemp - 32) * 5.0 / 9.0; cout << "Double precision : "; cout << dtemp << "F is " << temp << "C\n";; }

By: Nouf Almunyif Recursion

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. 88

General form void recurse() { recurse(); //Function calls itself } 89

Finding Factorial 5! = 5*4*3*2*1 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 90

Finding Factorial  #incloud ;  Using nampespace std;  Void main() {  int n,factorial,i;  cout << "Enter a positive integer: ";  cin >> n;  for (i = 1; i <= n; i++)  { if (i == 1)  factorial = 1;  Else  factorial = factorial * i; }}  cout << "The factorial of " << n << " is " << factorial << endl; }} 91

Finding Factorial Recursively //Recursive factorial Function #include Int factorial(int N); Void main() {int num; cout<<“Enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); } Int factorial( int N) { if ( N <= 1) //the base case return 1; else return N * factorial (N - 1); } //Recursive factorial Function #include Int factorial(int N); Void main() {int num; cout<<“Enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); } Int factorial( int N) { if ( N <= 1) //the base case return 1; else return N * factorial (N - 1); } N=4 Retrun 4 *factorial(3) N=3 Retrun 3 *factorial(2) N=2 Retrun 2 *factorial(1) N=1 Retrun 1 Enter a positive integer : 4 1 2*1 = 2 2 3*2 =6 6 4*6=24 Factorial = 24 92

Example printing number counting down #include using namespace std; void myMethod( int counter) { if(counter == 0) return; // no value returning just for EXIT the function else { cout<<counter<<endl; myMethod(--counter); return; // no value returning just for EXIT the function } void main() { int input; cout<<"enter positive number "; cin>>input; myMethod(input); } 93