0% found this document useful (0 votes)
18 views37 pages

c++ Chapter 2 Function

Chapter Three discusses functions in C++, defining them as self-contained blocks of code that perform specific tasks and can be called from various points in a program. It covers types of functions, including standard library functions and user-defined functions, along with their declaration, definition, and parameter passing methods. The chapter also touches on advanced topics such as recursion, function overloading, and inline functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views37 pages

c++ Chapter 2 Function

Chapter Three discusses functions in C++, defining them as self-contained blocks of code that perform specific tasks and can be called from various points in a program. It covers types of functions, including standard library functions and user-defined functions, along with their declaration, definition, and parameter passing methods. The chapter also touches on advanced topics such as recursion, function overloading, and inline functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter Three

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

1. Standard Library Functions: Predefined in C++


– are built-in functions that your program can call.
• For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to
another location
– are the functions which are declared in the C++ header
files such as ceil(x), cos(x), exp(x), etc.

2. User-defined Function: Created by users.

• In this chapter, we will focus mostly on user-defined


functions.
3
User-defined Function
• C++ allows the programmer to define their own
function.
• A user-defined function is a group codes 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/ creating a function.
2. Defining the function.
4
Function Declaration
• Function declaration tells the compiler about a
function name and how to call the function.
• In general, all functions in a C++ program must be
declared except the function main
• It is also called function prototype, consists of:
– function type (which means a Return type)
– function name
– list of function parameter types enclosed parenthesis
(which indicates the parameters)
– Terminal semicolon (;)

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.

• The syntax to define a function is:


returnType functionName (parameter1, parameter2,...)
{
// function body
}.

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);

cout<<"Your Name: "<<name<<endl;


cout<<"Your Departement: "<<dept;
} 8
Example: a C++ program which reads two integer and display
their sum

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.

• 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.

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.

• Now, the question is where is the definition of that


function? How does this function calculate and return
the result?

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,

• Then line 11 displays the result of the function.

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);

• When a function call is encountered, the program


control passes to the called function and then 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.
16
Parameter Passing

• There are two ways to pass value or data to


function in C++ language: call by value and call
by reference.
• Original value is not modified in call by value but
it is modified in call by reference.

17
Parameter Passing: By value

• When the formal parameters in a function are


declared as regular variable then the compiler will
understand 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.
– For example in the above sample code a and var1 are
similar in type and b and var2 are similar in type.
18
Parameter Passing: By value

• If you change the value of function parameter, it is


changed for the current function only. It will not
change the value of variable inside the caller method
such as main().
• The actual parameters in function calls can be
constants, variables, or expressions.
• Therefore, parameter passing by value copies the
values of variables but never the variables themselves.

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

• 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.
25
Default Values in Parameters

// default values in functions int main ()


#include <iostream.h> {
int divide (int a, int b=2) cout << divide (12);
{ cout << endl;
int r; cout << divide (20,4);
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 value
second parameter is 2 and the result will be 6.
26
Default Values in Parameters

// default values in functions int main ()


#include <iostream.h> {
int divide (int a, int b=2) cout << divide (12);
{ cout << endl;
int r; cout << divide (20,4);
r=a/b; return 0;
return (r); }
}

• 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 which is 4 and the result will be 5.

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

• Functions can have the same name if their parameter


types or number are different.
• Note that a function cannot be overloaded only by its
return type. At least one of its parameters must have a
different type.

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

• If a function is declared with the keyword inline, the


compiler does not create a real function, instead, it
copies the code from the inline function directly into
the calling function.
• No jump is made; it is just as if you had written the
statements of the function right into the calling
function.
• This avoid control from jumping to another location.

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

You might also like