c++ Chapter 2 Function
c++ Chapter 2 Function
Functions
1
What is Function?
• 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.
– is a group of statements that is given a name, and
which can be called from some point of the program.
– allows to structure programs in segments of code to
perform individual tasks.
– should be declared before we use it.
– You can pass data, known as parameters, into a
function.
2
Types of Function
5
Function Declaration
• The general form of a function prototype is the same
as a function definition, except that no body is
present.
• Syntax:
– returnType functionName (parameter1, parameter2,...);
• Example:
– int sum(int, int);
– float average(float, float, float)
– bool isfull();
– void Display(); 6
Function Definition
• A function declaration tells the compiler about a
function's name, return type, and parameters.
• However, a function definition provides the actual
body of the function.
7
Function Definition: Example
int sum(int a, int b) float average(float x, float y, float z)
{ {
int c = 0; float average = 0;
c = a + b; average = (x + y + z)/3;
return c; return average;
} }
void Display()
{
char name[50], char dept[30];
cout<<"Enter your Full Name: ";
gets(name);
cout<<"Enter your Departement: ";
gets(dept);
line 1 #include<iostream.h>
line 2 int sum(int, int); // function declaration
line 3 int main() {
line 4 int var 1, var2, result;
line 5 result = 0;
line 6 cout<<"Enter the first number\n";
line 7 cin>>var1;
line 8 cout<<"Enter the second number\n";
line 9 cin>>var2;
line 10 result = sum(var1,var2); line 13 int sum(int a, int b)
line 11 cout<<"SUM = "<<result; line 14 {
line 12 } line 15 int c=0;
line 16 c = a + b;
line 17 return c;
line 18 }
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.
10
• Line 10 may appear new for you. It is very simple,
– 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.
11
• 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,
12
• 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 (var1
and var2) at line 10 and assign them on the variables ‘a’
and ‘b’ on line 13 respectively.
– Now, the function sum knows the two values, it
calculates their sum and assigns the sum to variable ‘c’
at line 16.
13
• Note that c is a local variable which is declared inside the
body of the function sum.
– i.e. the scope of variable ‘c’ is limited to the body of the
function sum.
• (return c) makes the compiler take the value of c and go
back to line 10 from the main function.
– Remember that execution of program was taken from this
line (line 10) directly to line 13.
• Now, the value returned (i.e. ‘c’) will be assigned to the
variable ‘result ‘.
• Then line 11 (cout<<"SUM = "<<result;) will display the
content of result.
14
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.
15
Calling Functions
• 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.
Syntax: Function_Name (parameter1, parameter2, …);
Example: sum(var1, var2);
17
Parameter Passing: By value
19
Parameter Passing: By value
20
Parameter Passing: By Reference
• When passing parameter by reference, the reference or
address for actual parameters is passed to the function.
• 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.
• The ampersand (&) operator is used to specify that
their corresponding arguments are to be passed by
reference instead of by value.
21
Parameter Passing: By Reference
22
Parameter Passing: By Reference
// 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;
} 23
Functions with no type (the use of void)
• Any functions that don’t return any values are
declared as a 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.h> {
void printmessage () printmessage ();
{ return 0;
cout << "I'm a function!"; }
24
}
Default Values in Parameters
27
Recursion Function
• Recursion is the process of defining something in terms
of itself.
• 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.
• Sometimes it is called circular definition.
28
Recursion Function: Example
29
Recursion Function: Example
Recursive program that computes the factorial of an integer. For
example 3 factorial (3!) is1*2*3 = 6.
30
Overloaded Functions
31
Overloaded Functions: Example
Output:
• we have defined two functions with the same
name, ‘operate’, but one of them accepts two 10
parameters of type int and the other one accepts 2.5
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. 32
Inline Functions
33
Inline Functions: Example
34
Quiz (5%)
1. What is Function?
2. Write the syntax for Function Declaration.
3. Write the difference between parameter passing by
value and by reference.
4. what is overloaded function?
5. Write a C++ program to calculate the area (Length *
width) of rectangle using function.
35
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.
• Inline function
– A program to add two numbers using inline function
36
?
Thank You
37