Functions Function A function is a selfcontained block
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 1. 2. 3. 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. Func. Return. Type Func. Name ( type Param_1, type Param_2, …, type Param_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. Function. Name ( arg_1, arg_2, …, arg_n);
Function Definition � 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. Func. Return. Type Func. Name ( Parameter List ) { statement 1; statement 2; . . . }
Example #include <iostream> Function Declaration using namespace std; int addition (int a, int b); int main () { Function Call int z; z = addition (5, 3); cout << "The result is " << z; return 0; } Function Definition int addition (int a, int b) { int r; r=a+b; return (r); 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 () I'm a function ! { printmessage (); return 0; }
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 squaren”; 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); int main ( ) { starline ( ‘*’, 30 ); cout<<“Hello World”; starline ( ‘+’, 30); return 0; } // starline function definition void starline (char ch, int n ) { for ( int j=0; j < n; j++ ) cout<<ch; cout<<endl; } //function declaration //function Call //function call //function Declarator //function body
Passing Variables as Arguments int calculate. Sum ( int, int ); int main ( ) { int a, b, c, sum; cout<<“Enter any three Numbers=“; cin>> a >> b >> c; sum = calculate. Sum( a, b, c ); cout<<“Sum of three number =” << sum; return 0; } int calculate. Sum ( 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. calculate. Sum (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 square. By. Value( int ); void square. By. Reference( int & ); int main() { int x = 2; int z = 4; // demonstrate square. By. Value cout << "x = " << x << " before square. By. Valuen"; cout << "Value returned by square. By. Value: “<< square. By. Value( x ) << endl; cout << "x = " << x << " after square. By. Valuen" << endl;
Contd… // demonstrate square. By. Reference cout << "z = " << z << " before square. By. Reference" << endl; square. By. Reference( z ); cout << "z = " << z << " after square. By. Reference" << endl; return 0; } // end main // square. By. Value multiplies number by itself, stores the // result in number and returns the new value of number int square. By. Value( int number ) { return number *= number; // caller's argument not modified }
Contd… // square. By. Reference multiplies number. Ref by itself and // stores the result in the variable to which number. Ref // refers in function main void square. By. Reference( int &number. Ref ) { number. Ref *= number. Ref; // caller's argument modified }
Output x = 2 before square. By. Value returned by square. By. Value: 4 x = 2 after square. By. Value z = 4 before square. By. Reference z = 16 after square. By. Reference
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 � 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; } 31
#include <iostream. h> inline double cube( double side ) return side * side; // calculate cube } int main() { cout << "Enter the side length of your cube: "; double side. Value; cin >> side. Value; // calculate cube of side. Value and display result cout << "Volume of cube with side " << side. Value << " is " << cube( side. Value ) << 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 my. Function( int x = 1, int y = 2, int z = 3 ); � my. Function(3) �x = 3, y and z get defaults (rightmost) � my. Function(3, �x 34 5) = 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 box. Volume( 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: " << box. Volume(); // specify length; default width and height cout << "nn. The volume of a box with length 10, n“ << "width 1 and height 1 is: " << box. Volume( 10 ); // specify length and width; default height cout << "nn. The volume of a box with length 10, n" << "width 5 and height 1 is: " << box. Volume( 10, 5 );
// specify all arguments cout << "nn. The volume of a box with length 10, n“ << "width 5 and height 2 is: " << box. Volume( 10, 5, 2 ) << endl; return 0; } // end main // function box. Volume calculates the volume of a box int box. Volume( int length, int width, int height ) urn length * width * height; } // end function box. Volume
Output The default box volume is: 1 The volume of a box with length 10, width 1 and height 1 is: 10 The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, 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) 41
#include <iostream. h> quare for int values cout << "Called square with int argument: " << x << endl; t version of function square uare for double values ble y ) cout << "Called square with double argument: " << y << endl; ble version of function square
int main() { int. Result = square( 7 ); // calls int version double. Result = square( 7. 5 ); // calls double version cout << "n. The square of integer 7 is " << int. Result << "n. The square of double 7. 5 is " << double. Result << 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 = π × r 2 � 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 1. 2. 3. Automatic External Static
�Life time �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 is not used usually. e. g. auto int x; auto float y; keyword
Contd… � Life time � 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 � 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 � 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 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 � 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 56
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) 57
#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! 2! 3! 4! 5! 6! 7! 8! 9! 10! = = = 1 1 2 6 24 120 720 5040 40320 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) 60
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.
- Slides: 66