Chapter one
Functions
1
Outline
1. Introduction to function
2. Declaration of function
3. Definition of functions
4. Calling function and Scope of Variables
5. Function Arguments
6. Return Values
7. Default Parameters
8. Parameters passing
9. Function Overloading
10.Recursive function
Functions
• Function:
– is a self-contained block of code that performs a
specific task of the same kind.
– is a block of code which only runs when it is called.
– allow to structure programs in segments of code to
perform individual tasks.
– You can pass data, known as parameters, into a
function.
– is a group of statements that is given a name, and
which can be called from some point of the
program.
3
Types:
• Standard Library Functions: Predefined in C++
• User-defined Function: Created by users.
In this chapter, we will focus mostly on user-defined functions.
User-defined function:
• C++ allows the programmer to define their own function.
• A user-defined function groups code to perform a specific task
and that group of code is given a name (identifier).
• When the function is invoked from any part of the program, it
all executes the codes defined in the body of the function.
Steps to have user-defined function:
1 declaring/ create function.
2 define function.
Function Declaration
• tells the compiler about a function name and how to call the
function.
• also called function prototype, consists of:
– function type// Return type
– function name
– list of function parameter types enclosed parenthesis//
parameters
– Terminal semicolon (;)
The syntax to declare a function is:
returnType functionName (parameter1, parameter2,...);
6
Cont..
• The general form of a function prototype is the same
as a function definition, except that no body is
present.
Example: int CalcAverage(int ,int);
7
Function Definition
• A function declaration tells the compiler about a
function's name, return type, and parameters.
• A function definition provides the actual body
of the function.
The syntax to define a function is:
returnType functionName (parameter1, parameter2,...)
{
// function body
}
8
Example: reads two integers and displays their sum
line 1 #include<iostream.h> line 11 cout<<"SUM = "<<result;
line 2 int sum(int, int); // function line 12 }
declaration
line 3 int main() { line 13 int sum(int a, int b)
line 4 int var2,var1,result; line 14 {
line 5 result = 0; line 15 int c=0;
line 6 cout<<"Enter the first line 16 c = a + b;
number\n"; line 17 return c;
line 7 cin>>var1; line 18 }
line 8 cout<<"Enter the second number\n";
line 9 cin>>var2;
line 10 result = sum(var1,var2);
9
Now let’s have a step by step look at the above program.
• Line 2 (int sum(int, int);) ,
– declares the function with the name as sum , the type of the
function is int, it takes two integer parameter of type int each.
• The code from line 4 up to line 9 should be familiar to you.
– The user is prompted to enter two integer value and these values
are assigned to var1 and var2 respectively.
• Line 10 may appear new for you. It is very simple, here we go,
– The expression result = sum(var1,var2); is a call to the function
sum.
– In other words, we are sending the two integer values provided
by the user to the function which will calculate and return the sum
of the two values.
• Now, the question is where is the definition of that function? How
does this function calculate and return the result.?
10
• After line10, execution of program will directly goes
to line 13 where the definition of the function is
located.
• The code from line 13 to line 17 gives us the reply
to the above questions.
– This part of the program i.e line 13 through line 18
, is the definition of the function sum,
11
• Line 13 (int sum(int a, int b) -
– indicates the starting of the function definition.
– This statement means , this function is named as sum
, it takes two parameters send to it from somewhere in the
main function by a function call(line 10).
– Statement in line 13 , will receive the two values (val1, and
val2) at line 10 and assign them on the variables ‘a’ and ‘b’
on line 13 respectively.
– Now, the function sum knows the two value , it calculated
their sum and assigns the sum to variable ‘c’ at line 16.
– Note that c is declared inside the body of the function sum. So,
this is known only in the body of this function. In Other words,
the scope of ‘c’ limited to the body of the function sum. After
calculating the sum at line 17
12
• ( return c) makes the compiler take the value of c and go back
to line 10 from.
• Remember that execution of program was taken from this line
directly to line 13.
• Now, the value returned i.e ‘c’ will be assigned to the variable
‘result ‘ at line17.
• The statement following this line is cout<<"SUM
= "<<result;. This will display the content of result to the visual
display unit.
• Note: Before a function is called, it must be either defined or
declared by a prototype in the source file
13
Calling Functions
• To use a function, you will have to call or invoke that function.
• When a program calls a function, program control is transferred
to the called function.
• A called function performs defined task and when its return
statement is executed or when its function-ending closing brace
is reached, it returns program control back to the main program.
• To call a function, you simply need to pass the required
parameters along with function name, and if function returns a
value, then you can store returned value.
14
• A function call requires the name of the function followed by
a list of actual parameter (arguments), if any, enclosed in
parentheses ends with semicolon.
sum(var1,var2);
function_name( );
• When a function call is encountered, the program control
passes to the called function. Next, the code corresponding
to the called function is executed.
• After the function body completes its execution, the program
control goes back to the calling function.
15
Parameter Passing
• By value
– If the formal parameters in a function are declared as regular
variable then the compiler understands that the programmer
intends to pass parameters by value.
– the values of the actual parameters are copied to the
memory locations of the corresponding formal parameters
in the called function’s data area.
– In parameter passing by value, the actual and formal parameters must be
of similar type. (In the above sample code a and var1 are similar in type
and b and var2 are similar in type).
– The actual parameters in function calls can be constants, variables,
or expressions.
• copies of their values but never the variables
themselves
16
By Reference
– W hen passing parameter by reference, the reference or
address for actual parameters is passed to the function so
that any change done to the variable affects the values of the
actual parameters.
– This ampersand is what specifies that their
corresponding arguments are to be passed by
reference instead of by value.
– When a variable is passed by reference we are not passing a
copy of its value, but we are somehow passing the variable
itself to the function and any modification that we do to
the local variables will have an effect in their counterpart
variables passed as arguments in the call to the function.
17
// passing parameters by reference
#include <iostream>
using namespace std;
void duplicate (int& a, int& b, int& c){
a*=2;//a=a*2
b*=2;
c*=2;}
int main (){
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" <<z;
return 0;
}
18
Functions with no type (the use of void)
• functions that don’t return values are declared void
• Imagine that we want to make a function just to
show a message on the screen.
• We do not need it to return any value. In this case we
should use the void type specifier for the function.
• This is a special specifier that indicates absence of type.
// void function example int main ()
#include <iostream> {
void printmessage () printmessage ();
{ return 0;
cout << "I'm a function!"; }
}
19
Default Values in Parameters
• When declaring a function we can specify a default
value for each of the last parameters.
• This value will be used if the corresponding
argument is left blank when calling to the function.
• To do that, we simply have to use the assignment
operator and a value for the arguments in the function
declaration.
• If a value for that parameter is not passed when the
function is called, the default value is used, but if a value
is specified this default value is ignored and the passed
value is used instead.
20
// default values in functions #include int main (){
<iostream> cout << divide (12);
int divide (int a, int b=2) cout << endl;
{ cout << divide (20,4);
int r; r=a/b; return 0;
return (r); }
}
In the First call:
divide (12) we have only specified one argument, but the function divide
allows up to two. So the function divide has assumed that the
second parameter is 2 since that is what we have specified to
happen if this parameter was not passed
In the second call:
divide (20,4) there are two parameters, so the default value for b (int
b=2) is ignored and b takes the value passed as
argument, that is 4,
21
Recursion
• A recursion function is one that calls itself
repetitively until a final call is made.
• A function is said to be recursive if a statement in the
body of the function calls itself.
• Recursion is the process of defining something in
terms of itself.
• sometimes called circular definition.
22
23
Exercises
• Recursive program that computes the factorial of an integer
– 3 factorial is1x2x3,or6.Bothfactr()
24
Overloaded Functions
• functions can have the same name if their
parameter types or number are different.
• Notice that a function cannot be overloaded only
by its return type. At least one of its parameters must
have a different type.
25
// overloaded function int main (){
int x=5,y=2;
#include <iostream.h> float n=5.0,m=2.0;
int operate (int a, int b) cout << operate (x,y);
{ cout << "\n";
cout << operate (n,m);
return (a*b); cout << "\n";
} return 0;
float operate (float a, float b) }
{
return (a/b); 10
} 2.5
• we have defined two functions with the same name, ‘operate’, but one of
them accepts two parameters of type int and the other one accepts them of
type float.
• The compiler knows which one to call in each case by examining the types
passed as arguments when the function is called.
26
Lab Class
• Function
– A program to compute area of rectangle
Hint: area=length * width
• Default value example
– Write a program to add two numbers.
• Recursive function
– A program to calculate factorial of any positive number
using recursive function.
• Overloaded function/ function overloading
– A program to compute all the arithmetic operations like
+, -, * and / with a Menu Driven.
27
Thank You
28