Functions.

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

Chapter 7: User-Defined Functions II
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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
CPSC230 Computers & Programming I Lecture Notes 20 Function 5 Dr. Ming Zhang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
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.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Functions. 3Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece more manageable than the original program.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
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.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions.
1 Chapter 3 - Functions Outline 3.1Introduction 3.2Program Components in C++ 3.3Math Library Functions 3.4Functions 3.5Function Definitions 3.6Function.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
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.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
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)
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.
 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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
C++ Programming Lecture 12 Functions – Part IV
Programming Fundamentals Enumerations and Functions.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 15 - C++ As A "Better C"
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
Topic 6 Recursion.
Dr. Shady Yehia Elmashad
Chapter 7: User-Defined Functions II
IS Program Design and Software Tools Introduction to C++ Programming
Chapter 3 - Functions Outline 3.1 Introduction
Functions and an Introduction to Recursion
CSC113: Computer Programming (Theory = 03, Lab = 01)
FUNCTIONS IN C++.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Dr. Shady Yehia Elmashad
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
Functions.
Functions Najah Alsubaie Kingdom of Saudi Arabia
Chapter 5 - Functions Outline 5.1 Introduction
Dr. Shady Yehia Elmashad
Chapter 3 - Functions Outline 3.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
FUNCTIONS& FUNCTIONS OVERLOADING
Chapter 6 - Functions Outline 5.1 Introduction
Chapter 3 - Functions Outline 3.1 Introduction
Computing Fundamentals
Variables have attributes
Functions and an Introduction to Recursion
Chapter 15 - C++ As A "Better C"
Chapter 3 - Functions Outline 3.1 Introduction
Functions Chapter No. 5.
Presentation transcript:

Functions

Function A function is a self-contained block of statements that performs coherent task of some kind. OR A function groups a number of program statements into a unit and gives it a name. This unit can then be invoked from other parts of the program.

Writing Functions in C++ 3 things associated with functions Function Declaration (Function Prototype) Function Call Function Definition

Function Declaration In C++, you must declare every identifier before it can be used. In the case of functions, a function’s declaration must physically precede any function call. A function declaration announces to the compiler the name of the function, the data type of the function’s return value and the data type of the parameters it uses. Function declarations are also called prototypes. FuncReturnType FuncName ( type Param_1, type Param_2, …, type Param_n) ;

FunctionName ( arg_1, arg_2, …, arg_n); Function Call A statement that transfers control to a function. In C++, this statement is the name of the function, followed by the list of arguments. To call a function, we use its name as a statement, with the arguments in parentheses following the name. A function call in a program results in the execution of the body of the called function. FunctionName ( arg_1, arg_2, …, arg_n);

Function Definition FuncReturnType FuncName ( Parameter List ) Function Definition consists of two parts: the function heading or declarator and the Function body. The function body is composed of statements that make up the function, delimited by braces. The heading or declarator must agree with the function declaration. It must use the same function name, have the same argument types in the same order, and have the same function return type. FuncReturnType FuncName ( Parameter List ) { statement 1; statement 2; . }

Example #include <iostream> using namespace std; int addition (int a, int b); int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0;} int addition (int a, int b) int r; r=a+b; return (r); } Function Declaration Function Call Function Definition The result is 8

Parameters vs. Arguments Parameters used in function definition whereas Arguments used in function call. The sequence of the arguments in the function call should be same as the sequence of the parameters in the parameter list of the function declaration. The data types of the arguments should correspond with the data types of the parameters. When a function call is made arguments replace the parameters of the function.

return statement A return statement is used to exit from the function where it is. It returns the execution of the program to the point where the function call was made. It returns a value to the calling code. The general form of the return statement is return expression;

Eliminating the Declaration The second approach of inserting a function into a program is to eliminate the function declaration and place the function definition in the listing before the first call of the function.

Example #include <iostream.h> int addition (int a, int b) { int r; r=a+b; return (r); } int main () int z; z = addition (5,3); cout << "The result is " << z; return 0;} Function Definition Function Call The result is 8

Example #include <iostream> void printmessage () { cout << "I'm a function!"; } int main () printmessage (); return 0; I'm a function !

Advantages of using Functions Code becomes more readable, easy to modify. Code becomes compact and small. Reduces the complexity in a program by reducing the code. It also reduces the time to run a program (by making code compact and small). Functions are helpful in generalizing the program. Testing and debugging is easier.

Example 3 int square (int); int main () { int n; cout<<“” Enter any number to find its square\n”; cin>>n; cout<<“Square of”<<n<<“is”<<square(n); return 0;} int square(int x) return (x*x); }

Example 4 int factorial (int); int main () { int n; cout<<"Enter a number to find its factorial"<<endl; cin>>n; cout<<n<<"! ="<<factorial(n)<<endl; return 0;} int factorial (int x) int result=1; for (int i=1; i<=x;i++) result=result*i; return(result); }

Example 4 Another way void factorial (int); int main () { int n; cout<<"Enter a number to find its factorial"<<endl; cin>>n; factorial(n); return 0;} void factorial (int x) int result=1; for (int i=1; i<=x;i++) result=result*i; cout<<x<<"!="<<result<<endl; }

Passing Arguments to Function An argument is a piece of data, of any data type, passed from a program to the function. Arguments allow a function to operate with different values. Arguments can be passed in two ways Passing by Value Passing by Reference

Passing Constant as Arguments #include <iostream.h> void starline( char, int); //function declaration int main ( ) { starline ( ‘*’, 30 ); //function Call cout<<“Hello World”; starline ( ‘+’, 30); //function call return 0; } // starline function definition void starline (char ch, int n ) //function Declarator for ( int j=0; j < n; j++ ) //function body cout<<ch; cout<<endl; }

Passing Variables as Arguments int calculateSum ( int, int, int ); int main ( ) { int a, b, c, sum; cout<<“Enter any three Numbers=“; cin>> a >> b >> c; sum = calculateSum( a, b, c ); cout<<“Sum of three number =” << sum; return 0; } int calculateSum ( int x, int y, int z) int result; result = x+y+z; return result; }

Returning Values From When a function completes its execution, it can return a single value to the calling program. Usually this return value consists of an answer to the problem the function has solved. When a function returns a value, the data type of this value must be specified. The function declaration do this by placing the data type before the function name in the declaration and the definition. You should always include a function’s return type in the function declaration. If you don’t use a return type in the declaration, the compiler will assume that the function returns an int value. calculateSum (int , int , int)

Reference Arguments

Reference Arguments Passing arguments by reference is a mechanism in which a reference(memory address) to the original variable, in the calling program, is passed to the function. When arguments are passed by value, the called function creates a new variable of the same type as an argument and copies the argument’s value into it.

Reference Arguments An important advantage of passing reference arguments is that the function can access the actual variables in the calling program. When the function is called, the reference argument and the variable name, in the calling function, become synonyms for the same location in the memory. We can only use variables when we are passing arguments by reference. Whereas, we can use variables as well as constant when we are passing arguments by value.

Example #include <iostream> int squareByValue( int ); void squareByReference( int & ); int main() { int x = 2; int z = 4; // demonstrate squareByValue cout << "x = " << x << " before squareByValue\n"; cout << "Value returned by squareByValue: “<< squareByValue( x ) << endl; cout << "x = " << x << " after squareByValue\n" << endl;

Contd… // demonstrate squareByReference cout << "z = " << z << " before squareByReference" << endl; squareByReference( z ); cout << "z = " << z << " after squareByReference" << endl; return 0; } // end main // squareByValue multiplies number by itself, stores the // result in number and returns the new value of number int squareByValue( int number ) { return number *= number; // caller's argument not modified }

Contd… // squareByReference multiplies numberRef by itself and // stores the result in the variable to which numberRef // refers in function main void squareByReference( int &numberRef ) { numberRef *= numberRef; // caller's argument modified }

Output x = 2 before squareByValue Value returned by squareByValue: 4 x = 2 after squareByValue   z = 4 before squareByReference z = 16 after squareByReference

Activity Write a function swap that interchanges the values of the two variables Call the function by value and by reference to see the difference in output.

Inline functions

Inline Functions Execution time overhead involved in function call. Inline functions reduces this overhead especially for small functions. The keyword “inline” before the function’s return type in function definition is an indication to compiler to generate a copy of function code to avoid function call

Inline Functions Inline functions Example Keyword inline before function Asks the compiler to copy code into program instead of making function call Reduce function-call overhead Good for small, often-used functions Example inline double cube(double s ) { return s * s * s; }

Enter the side length of your cube: 3.5 #include <iostream.h> inline double cube( double side ) { return side * side * side; // calculate cube } int main() cout << "Enter the side length of your cube: "; double sideValue; cin >> sideValue; // calculate cube of sideValue and display result cout << "Volume of cube with side " << sideValue << " is " << cube( sideValue ) << endl; return 0; } // end main Enter the side length of your cube: 3.5 Volume of cube with side 3.5 is 42.875

Default Arguments

Default Arguments Function call with omitted parameters If not enough parameters, rightmost go to their defaults Set defaults in function prototype int myFunction( int x = 1, int y = 2, int z = 3 ); myFunction(3) x = 3, y and z get defaults (rightmost) myFunction(3, 5) x = 3, y = 5 and z gets default

Contd… If the function prototype is omitted because the function definition also serves as the prototype, then the default arguments should be specified in the function header. Default arguments also can be used with inline functions.

#include <iostream.h> // function prototype that specifies default arguments int boxVolume( int length = 1, int width = 1, int height = 1 ); int main() { // no arguments--use default values for all dimensions cout << "The default box volume is: " << boxVolume(); // specify length; default width and height cout << "\n\nThe volume of a box with length 10,\n“ << "width 1 and height 1 is: " << boxVolume( 10 ); // specify length and width; default height cout << "\n\nThe volume of a box with length 10,\n" << "width 5 and height 1 is: " << boxVolume( 10, 5 );

// specify all arguments cout << "\n\nThe volume of a box with length 10,\n“ << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 ) << endl; return 0; } // end main // function boxVolume calculates the volume of a box int boxVolume( int length, int width, int height ) { return length * width * height; } // end function boxVolume

Output The default box volume is: 1   The volume of a box with length 10, width 1 and height 1 is: 10 width 5 and height 1 is: 50 width 5 and height 2 is: 100

Activity Write a function to find the power of a number. The function accepts the base and exponent and if no exponent value provided it takes it as 1 (default value of exponent=1)

Function Overloading

Function Overloading Function overloading Functions with same name and different parameters 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; } Overloaded functions distinguished by signature Based on name and parameter types (order matters)

#include <iostream.h> // function square for int values int square( int x ) { cout << "Called square with int argument: " << x << endl; return x * x; } // end int version of function square // function square for double values double square( double y ) cout << "Called square with double argument: " << y << endl; return y * y; } // end double version of function square

int intResult = square( 7 ); // calls int version int main() { int intResult = square( 7 ); // calls int version double doubleResult = square( 7.5 ); // calls double version cout << "\nThe square of integer 7 is " << intResult << "\nThe square of double 7.5 is " << doubleResult << endl; return 0; } // end main Called square with int argument: 7 Called square with double argument: 7.5   The square of integer 7 is 49 The square of double 7.5 is 56.25

Activity Overload the area function for finding the area of triangle, circle, rectangle. Area of triangle= ½ × base × height Area of circle = π × r2  Area of rectangle = width × height

Storage Class

Storage Class Storage class of variable determines which part of the program can access the variable and how long it stays in existence. Three storage classes Automatic External Static

Life time Visibility/Scope The time period between the construction and destruction of variable is the life time of that variable. Visibility/Scope The locations within the program from where the variable can be accessed.

1. Automatic Variables All the local variables to the function are automatic. Since automatic by default, therefore auto keyword is not used usually. e.g. auto int x; auto float y;

Contd… Life time Visibility/Scope Initialization When the function is called automatic variables are created i.e. memory space is set aside for them and when control is passed back to the calling program they are destroyed and their values are lost. Visibility/Scope Automatic variables are visible only within the function in which they are defined. Initialization When automatic variables are created, the compiler do not initialize them. Instead they are initialized with arbitrary value that may be 0 or something else.

2. External Variables Also called global variables. Defined outside the function. Visible to all functions that follow its definition.

Contd… Life time Visibility/Scope Initialization Exists for the whole life of the program Created (memory space set aside for them) when the program starts until it ends. Visibility/Scope Visible to all functions in a program that follows its definition. Initialization If external variable is not initialized explicitly then it is automatically initialized to 0 when it is created.

3. Static automatic Variables Static automatic variables are used when we require that a function remember its value between the subsequent calls i.e. when the function is not being executed.

Contd… Visibility Life time Initialization Static automatic variables have the same visibility as the local/automatic variables. i.e. visible to the function containing it. Life time is similar to the external variable, that is, it exists for the whole life of the program but it is created when the first call to the function is made. Initialization Initialization is performed just once, when the function is first called. Unlike ordinary automatic variables they are not reinitialized on the subsequent calls to the function

Example int count () { static int c=0; return ++c; } int main () cout<<"first call "<<count()<<endl; cout<<"second call "<<count()<<endl; cout<<"third call "<<count()<<endl; return 0; }

Recursion

Recursion Recursive functions If not base case Functions that call themselves The function actually knows how to solve only the simplest case(s), or so-called base case(s) (Can only solve a base case) If not base case Break problem into smaller problem(s) Launch new copy of function to work on the smaller problem (recursive call/recursive step) Slowly converges towards base case Function makes call to itself inside the return statement Eventually base case gets solved Answer works way back up, solves entire problem

Recursion Example: factorial n! = n * ( n – 1 ) * ( n – 2 ) * … * 1 Recursive relationship ( n! = n * ( n – 1 )! ) 5! = 5 * 4! 4! = 4 * 3!… Base case (1! = 0! = 1)

#include <iostream> using namespace std; long factorial(long ); // function prototype int main() { for ( int i = 0;i<= 10;i++ ) cout << i << "! = “<< factorial( i )<< endl; return 0; } long factorial(long number ) if ( number <= 1 ) return 1; else return number * factorial( number - 1 ); }

Output 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

Recursion vs. Iteration Repetition Iteration: explicit loop Recursion: repeated function calls Termination Iteration: loop condition fails Recursion: base case recognized Both can have infinite loops Balance between performance (iteration) and good software engineering (recursion)

int power( int bas, int expo ); int main() { int base , exponent; cout << "Input base and exponent: "; cin >> base >> exponent; cout << base << " raised to power " << exponent << " is: “<< power( base , exponent ) ; return 0; } int power( int bas , int expo ) if( expo == 1 ) return bas; else return ( bas * power( bas , expo -1 ) ); }

Activity 1 Write a function multiple that determines for a pair of integers whether the second is multiple of the first. The function should take two arguments and return true if the second is multiple of the first, false otherwise. Use this function in a program that inputs a series of pairs of integers.

Activity 2 Raising a number to a power p is the same as multiplying n by itself p times. Write a function called power that takes two arguments, a double value for n and an int value for p, and return the result as double value. Use default argument of 2 for p, so that if this argument is omitted the number will be squared. Write the main function that gets value from the user to test power function.

Activity 3 Write a function called zero_small() that has two integer arguments being passed by reference and sets the smaller of the two numbers to 0. Write the main program to access the function.

Activity 4 Write a function that receives two numbers as an argument and display all prime numbers between these two numbers. Call this function from main( ).

Activity 5 Write a function that, when you call it, displays a message telling how many times it has been called: “I have been called 3 times”, for instance. Write a main() program that calls this function at least 10 times.