Download presentation
Presentation is loading. Please wait.
1
Functions
2
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.
3
Writing Functions in C++
3 things associated with functions Function Declaration (Function Prototype) Function Call Function Definition
4
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) ;
5
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);
6
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; . }
7
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
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.
9
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;
10
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.
11
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
12
Example #include <iostream> void printmessage () {
cout << "I'm a function!"; } int main () printmessage (); return 0; I'm a function !
13
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.
14
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); }
15
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); }
16
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; }
17
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
18
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; }
19
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; }
20
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)
21
Reference Arguments
22
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.
23
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.
24
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;
25
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 }
26
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 }
27
Output x = 2 before squareByValue Value returned by squareByValue: 4 x = 2 after squareByValue z = 4 before squareByReference z = 16 after squareByReference
28
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.
29
Inline functions
30
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
31
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; }
32
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
33
Default Arguments
34
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
35
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.
36
#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 );
37
// 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
38
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
39
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)
40
Function Overloading
41
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)
42
#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
43
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
44
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
45
Storage Class
46
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
47
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.
48
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;
49
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.
50
2. External Variables Also called global variables.
Defined outside the function. Visible to all functions that follow its definition.
51
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.
52
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.
53
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
54
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; }
55
Recursion
56
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
57
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)
58
#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 ); }
59
Output 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 10! =
60
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)
61
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 ) ); }
62
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.
63
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.
64
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.
65
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( ).
66
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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.