0% found this document useful (0 votes)
16 views

CHapter 2 function

class note

Uploaded by

akliluasebot
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

CHapter 2 function

class note

Uploaded by

akliluasebot
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

COMPUTER PROGRAMMING-II

CHAPTER-Two
Working on Functions
CONTENTS

Introduction
Defining and Declaring Functions
Function passing
Scope of variables on functions
Inline function
Recursive functions
Tuesday, December 24, 2024 Abdela A. 2
Modularity
• Modular programming
– Breaking down the design of a program into individual
components (modules) that can be programmed and tested
independently
– A program divided into several smaller parts which can interact
• Modules
– Can be written and tested separately
– Testing is easier (smaller)
– Doesn't need to be retested
– Reduces length of program
– Hides details (abstraction)

Tuesday, December 24, 2024 Abdela A. 3


Function
• An important concept on programming is the ability to
break the program into smaller pieces as subroutines
this is called functions in c++.
• A subroutine is a portion of a code that can be called
from other routines..
• A function is a group of statements that is executed
when it is called from some point of the program.
• Every C++ program has at least one function that is the
main().main() is where every c++ program started
• When your program starts, main() is called
automatically.
Tuesday, December 24, 2024 Abdela A. 4
Cont…
• This method is called: Top-down design or
• Stepwise refinement or or graphically Divide and
Conquer.
• The subparts in other PLs – sub programs,
procedures , subroutines, ,modularity/module, etc
and all this in C++ its called functions
• One of the advantage of using a function to divide
program task into subtasks, that different people
can work on different sub tasks, when producing a
very large program
Tuesday, December 24, 2024 Abdela A. 5
Cont…
• A C++ program might contain more than one
function.
• In programming, function refers to a segment
that groups code to perform a specific task.
• Depending on whether a function is
predefined or created by programmer; there
are two types of function:
• User defined functions
• Built in functions(Library Function)

Tuesday, December 24, 2024 Abdela A. 6


Built in function(library function)
• Programmer can use library function by
invoking function directly; they don't need to
write it themselves.
• We need not to declare and define these
functions as they are already written in the C+
+ libraries such as iostream, cmath etc.
• We can directly call them when we need.
• are part of a compiler packages.
• They are supplied by the manufacture for your use.
• E.g pow(), sqrt(), etc.

Tuesday, December 24, 2024 Abdela A. 7


Built in math library function

Tuesday, December 24, 2024 Abdela A. 8


Built in….
• Here we are using built-in function pow(x,y) which is x to the power y.
• This function is declared in cmath header file so we have included the
file in our program using #include directive.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
/* Calling the built-in function * pow(x, y) which is x to the
power y * We are directly calling this function */
cout<<pow(2,5);
return 0;
}
Tuesday, December 24, 2024 Abdela A. 9
User-defined Function

• C++ allows 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 program, it all
executes the codes defined in the body of function

Tuesday, December 24, 2024 Abdela A. 10


Example
#include <iostream>
#include <math>
using namespace std;
//Declaring the function sum
int sum(int,int);
int main()
{ int x, y;
cout<<"enter first and second number: ";
cin>> x>>y;
cout<<"Sum of these two :"<<sum(x,y);
return 0; }
//Defining the function sum
int sum(int a, int b)
{
int c = a+b;
return c;
}
Tuesday, December 24, 2024 Abdela A. 11
Defining and Declaring functions
• So a function description consists of three parts
• Interface/prototype/Declaration
• Function call
• Function Definition
• The declaration tells the compiler the:
• Name
• Return type and
• Parameter of the function
• function definition tells the compiler how the
function works.
Tuesday, December 24, 2024 Abdela A. 12
The Declaration of a function
• If a user-defined function is defined after main() function,
compiler will show error.
• It is because compiler is unaware of user-defined
function, types of argument passed to function and
return type.
• In C++, function prototype is a declaration of function
without its body to give compiler information about user-
defined function.
• there is no body of function in prototype.
• A function declaration tells the compiler about a
function's name, return type, and parameters(signature).
Tuesday, December 24, 2024 Abdela A. 13
The Declaration of a function
• The declaration of a function is called its prototype or
interface
• its prototype specifies how it may be used.
• Is a statement - it ends with a semicolon
• Function prototype are normally placed before the
main() part of your program.
• It consists of three entities:
– return type,
– name,
– parameter list
Tuesday, December 24, 2024 Abdela A. 14
The syntax for function declaration/prototype
is:
type functionName (parameter_list);
• You can use either of the two ways on declaration:
double total_cost (int num, double price);
• Is equivalent to:
double total_cost (int, double);
• So it is possible that a function prototype doesn’t need
to contain names of parameters (num, price), but type
of parameter is essential.
• Parameter names are not important in function
declaration only their type is required
Tuesday, December 24, 2024 Abdela A. 15
Function Definition
• Tells the compiler how the function works.
• A function definition can be considered as a code for a small
program.
• A function definition provides the actual body of the function
• Writing the full body of function is known as defining a function.
• When the function is called, control is transferred to the first
statement of the function body.
• Then, other statements in function body are executed
sequentially.
• When all codes inside function definition is executed, control of
program moves to the calling program.

Tuesday, December 24, 2024 Abdela A. 16


Syntax of function definition

Tuesday, December 24, 2024 Abdela A. 17


Function definition
• A function definition consists of function header
and function body.
• Function Header
• Is written in the same way as function prototype,
the two basic things on the header are:
• on the header parameters must be named and
• the header doesn’t have a semi colon at the end.

example :double total_cost (int num, double price)


Tuesday, December 24, 2024 Abdela A. 18
Cont…
Function body
• Follows the function header and completes the function
definition.
• The body of the function contains the computational steps
(statements) that comprise the function.
• The function body consists of declarations and executable
statements enclosed with in square brackets {}.
• Thus a function body is just like the body of the main part
of a program.
• The value returned by the function is determined when the
function executes a return statement.

Tuesday, December 24, 2024 Abdela A. 19


Cont…
• A return statement consists of the keyword return followed
by an expression.
return;
return (expression);
• Statement after the return would not be executed, because
when the return statement is executed the function call
ends.
• So, a return statement terminates the execution of the
function.
• A function can have several return statements, although
one is preferable.
• Using a function involves ‘calling’ it.
Tuesday, December 24, 2024 Abdela A. 20
Function call
• While creating a C++ function, you give a definition
of what the function has to do.
• To use a function, you will have to call or invoke
that function.
• To execute the codes of function body, the user-
defined function needs to be invoked(called).
• 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
Tuesday, December 24, 2024 Abdela A. 21
Function call
A function call consists of:
– The function name
– Followed by the call operator brackets ()
– Inside which zero or more comma-separated
arguments appear.
– The number of arguments should match the number
of function parameters.
• Each argument is an expression whose type
should match the type of the corresponding
parameter in the function interface.

Tuesday, December 24, 2024 Abdela A. 22


Cont…
• When a function call is executed, the arguments are
first evaluated and their resulting values are assigned to
the corresponding parameters.
• The function body is then executed.
• Finally, the function return value (if any) is passed to the
caller.
• Since a call to a function whose return type is non-void
yields a return value, the call is an expression and may
be used in other expressions.
• A C++ program always begins its execution by the main
function that is why it calls the other functions.
Tuesday, December 24, 2024 Abdela A. 23
A program to demonstrate function declaration,
function calling and function definition in C++
====================================
#include<iostream.h>
void main (void)
{
void display (void); // function declaration
display (); // function calling
}
void display (void) // function definition
The main function
{
invokes this line of
cout<<“Hello world!”<<endl; code
}
Tuesday, December 24, 2024 Abdela A. 24
A program to demonstrate function declaration,
function calling and function definition in C++
====================================
#include<iostream.h>
void main (void)
{
void display (void); // function declaration
display (); // function calling
}
void display (void) // function definition
The main function
{
invokes this line of
cout<<“Hello world!”<<endl; code
}
Tuesday, December 24, 2024 Abdela A. 25
A program to demonstrate function prototype and
function definition together in C++
====================================
#include<iostream.h>
void display (void); // function prototype
void main (void)
{
display (); // function calling
}
void display (void) // function definition
{
cout<<“Hello world!”<<endl;
}
Tuesday, December 24, 2024 Abdela A. 26
A program to demonstrate separated function prototype and
function definition in C++ (no semi colon)
====================================
#include<iostream.h>
void display (void) // function definition
{
cout<<“Hello world!”<<endl;
}
void main (void)
{
display (); // function calling
}

Tuesday, December 24, 2024 Abdela A. 27


EXAMPLE
#include <iostream>
using namespace std;
int add(int, int);
int main()
{
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin >> num1 >> num2;
sum = add(num1, num2);// Function call
cout << "Sum = " << sum;
return 0;
}
int add(int a, int b) // Function definition
{
int add;
add = a + b; // Return statement return add;
}
Tuesday, December 24, 2024 Abdela A. 28
Exercise on function
• write a c++ function that display the following information

Tuesday, December 24, 2024 Abdela A. 29


Exercise on function
• Write a function that display the following
information

Tuesday, December 24, 2024 Abdela A. 30


Exercise
• Write a function that accepts three parameters perform sum, multiplication
and average
• Write a float function triangle() that computes the area of a triangle using
its two formal parameters h and w, where h is the height and w is the
length of the bases of the triangle.
• Write a float function rectangle() that computes and returns the area of a
rectangle using its two float formal parameters h and w, where h is the
height and w is the width of the rectangle
• Write a function called isEven() that uses the remainder operator(%) to
determine whether an integer is even or not

Tuesday, December 24, 2024 Abdela A. 31


Actual and Formal Arguments
• The arguments may be classified under two groups,
– Actual argument and
– Formal arguments.
• Actual arguments- are variables or an expressions
contained in a function call that replaces the formal
parameter which is a part of the function declaration
or function definition.
• Sometimes, a function may be called by a portion of
a program with some parameters and these
parameters are known as the actual arguments
Tuesday, December 24, 2024 Abdela A. 32
#include<iostream.h>
void output (int x, int y); // function declaration
void main ()
{
int x, y;
_______________
_______________
output(x, y); // x and y are the actual arguments
}

Tuesday, December 24, 2024 Abdela A. 33


Cont…
• Formal arguments- are the parameters
present in a function definition which may
also be called as dummy arguments or the parametric
variables.
• When the function is invoked, the formal
parameters are replaced by the actual
parameters.

Tuesday, December 24, 2024 Abdela A. 34


#include <iostream.h>
void output(int x, int y);
Void main ()
{
int x, y;
_____________
________________
output(x, y);
}
void output(int a, int b) // formal or dummy argument
{
// body of the function
}
Tuesday, December 24, 2024 Abdela A. 35
Passing Arguments to Function
• In programming, argument (parameter) refers
to the data which is passed to a function
(function definition) while calling it.
• C++ supports two types styles of passing or
calling parameters:
– calling by value and
– Calling by reference /Address
• The term call by value and call by reference
refer to a mechanism that is used in the
‘plugging in’ process.
Tuesday, December 24, 2024 Abdela A. 36
Call by Value
• This method copies the actual value of an argument
into the formal parameter of the function.
• In this case, changes made to the parameter inside
the function have no effect on the argument.
• As a result, if the function makes any changes to the
parameter, this will not affect the argument.
• The function receives a copy of the actual parameter
values.
• The function cannot change the values of the actual
parameters
Tuesday, December 24, 2024 Abdela A. 37
#include<iostream.h>
void func1 (int num);
void main ()
{ Output
int x = 10; X = 10
Num = 20
cout<<“ x = “<<x<<endl;
X = 10
func1 (x);
cout<<“x = “<<x<<endl;
}
void func1 (int num)
{
num += num;
cout<<“num = “<<num<<endl;
}
Tuesday, December 24, 2024 Abdela A. 38
Cont…
• Illustration of the above program
• The single parameter of func1 is a value parameter. As far
as this function is concerned, num behaves just like a local
variable inside the function.
• When the function is called and x is passed to it, num
receives a copy of the value of x.
• As a result, although num gets the value 10 and it returns
20 by the function, this does not affect x.
• Passing by value is important while the function doesn’t
need to modify the original variable in the coding program

Tuesday, December 24, 2024 Abdela A. 39


Cont…
• Arguments passed into the function are local to the function.
• Changes made to the arguments do not affect the value in
the call in function or main (). This is known as passing by
value, which means a local copy of each argument is made in
the function.
• In the call by value mechanism when the function is called
the formal parameters for the function (which are local
variables) are initialized to the value of the argument.
• A call by value is a means of substitution process.
• It is the value of the substituted variable that is plugged in,
not the variable it self.

Tuesday, December 24, 2024 Abdela A. 40


Call by Reference
• Passing an argument by reference allows the function to
change the value of the argument.
• When a function is called its arguments are substituted for
the formal parameters in the function definition, or in other
words the arguments are ‘plugged in’ for formal parameters.
• In call by reference parameter, for an input function we want
the variable (not the value of the variable) to be substituted
for the formal parameter.
• After the argument is substituted in, the code in the function
body is executed, and this code can change the value of the
argument variable.

Tuesday, December 24, 2024 Abdela A. 41


Cont…
• 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.
• In other words we access the variable from its memory and
return the value again to that memory whether it is
changed or not.
• A call by reference parameter must be marked in some way
so that compiler will know (differentiate) it from a call by
value parameter.

Tuesday, December 24, 2024 Abdela A. 42


Cont…
• The way that you indicate a call by reference parameter is
to attach the ampersand sign ‘&’ to the end of the type
name and before the parameter variable name, in the
formal parameter list, in both the function prototype and
the function definition. Such as:
• float salary (int &income, float &tax)
• An argument that is passed by a reference must be an
actual variable.
• It is not possible to pass a constant or an expression by
reference, because constants and expressions are read
only; value can not be assigned to them.
Tuesday, December 24, 2024 Abdela A. 43
The advantage of using a call by reference is
that function can access the actual variable in
the calling program. Without the ampersand
sign (&), we would have not passed the
variables by reference but, a copy of their
values.

void duplicate (int& a, int& b, int& c)

duplicate (x , y , z);
Tuesday, December 24, 2024 Abdela A. 44
#include<iostream.h>
#include<math.h>
void sqr (float &num);
void main()
{
float first;
cout<<“Enter the first number”;
cin>>first;
cout<<“Before num is: “<<first;
cout<<“\n In function ”;
sqr(first); // calls function
cout<<“After num is :”<<first;
}
void sqr (float &num)
{
num = sqrt(num);
cout<<“the square root is “ <<num<<“\n”;
}
Tuesday, December 24, 2024 Abdela A. 45
Write a program to swap two integers using call by value and
call by reference.

Tuesday, December 24, 2024 Abdela A. 46


Value vs reference

Tuesday, December 24, 2024 Abdela A. 47


Default Arguments
• The idea behind default argument is simple. If a function is
called by passing argument/s, those arguments are used by
the function.
• But if the argument/s are not passed while invoking a
function then, the default values are used.
• Default value/s are passed to argument/s in the function
prototype.
• 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.
Tuesday, December 24, 2024 Abdela A. 48
Default Arguments
• A default argument is a function argument that
has a default value provided to it.
• If the user does not supply a value for this
argument, the default value will be used.
• If the user does supply a value for the default
argument, the user-supplied value is used.
• Note : Only the trailing arguments can have
default values and therefore we must add
default values form right-to-left.
Tuesday, December 24, 2024 Abdela A. 49
Example

Tuesday, December 24, 2024 Abdela A. 50


//default values in functions
#include<iostream.h>
int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}
int main()
{
cout<<divide(12);
cout<<endl;
cout<<divide(20,5);
}
Tuesday, December 24, 2024 Abdela A. 51
Example
#include<iostream.h>
int Add(int x, int y=20, int z=30)
{ return x + y + z; }
void main()
{ int rs;
rs = Add(5);
cout<<"\n\tThe sum is : "<<rs;
rs = Add(4,8);
cout<<"\n\tThe sum is : "<<rs;
rs = Add(7,3,4);
cout<<"\n\tThe sum is : "<<rs; }
Output :
The sum is : 55
The sum is : 42
The sum is : 14
Tuesday, December 24, 2024 Abdela A. 52
Recursive Function
• A function which calls itself directly or indirectly again
and again is known as the recursive function.
• Recursive functions are very useful while constructing
the data structures like liked lists, double linked lists and
trees.
• There is a distinct difference between normal and
recursive functions.
• a normal function will be invoked by the main function
whenever the function name is used, whereas the
recursive function will be invoked by itself directly or
indirectly as long as the given condition is satisfied.
Tuesday, December 24, 2024 Abdela A. 53
For example,
#include<iostream.h>
void main (void)
{
void funct1(); // function declaration
_____________
_____________
funct1(); // function calling
}
void funct1() // function definition
{
_____________
_____________
funct1(); // function calls recursively
}
Tuesday, December 24, 2024 Abdela A. 54
Example on recursive function
• Example 1: 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)
– Example 2:: Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number sum of two previous ones
– Example of a recursive formula:
• fib(n) = fib(n-1) + fib(n-2)
Tuesday, December 24, 2024 Abdela A. 55
Exercise
1. write c++ function for factorial of given number
2. Write c++ function for Fibonacci series number
3. Write a function for combination and permutation of
a given number

Tuesday, December 24, 2024 Abdela A. 56


Inline Function
• In C++, we can create short functions that are not actually
called, rather their code is expanded in line at the point of
each invocation.
• This process is similar to using a function-like macro.
• To cause a function to be expanded in line rather than called,
precede its definition with the inline keyword.
• A function which is expanded in a line when it is called is
called inline function.
• It executes faster than other member function.
• It can be recursive.
• Its body does not contain if else, switch, loop, goto
statement.
• The inline keyword is preceded by function definition
Tuesday, December 24, 2024 Abdela A. 57
Write a program to find area of a circle using inline
function.
#include<iostream.h>
inline float area(int);
void main() {
int r;
cout<<“ Enter the Value of r: ”;
cin>>r;
cout<<” Area is: “ << area(r); }
inline float area (int a) {
return(3.14*a*a);}
Output:
Enter the Value of r:
7153.86
Tuesday, December 24, 2024 Abdela A. 58
Function overloading
• In compile time polymorphism, all information needed
to call a function is known during program compilation.
• Example: Function overloading and operator
overloading are used to achieve compile time
polymorphism
• It is the process by which a single function can perform
different task, depending upon no of parameters and
types of parameters
– Functions with same name and different parameters
– Should perform similar tasks

Tuesday, December 24, 2024 Abdela A. 59


Write a program to overload function area () to
calculate area of circle and area of a rectangle.
• #include <iostream.h>
• float area(int);
• int area(int, int);
• void main( ) {
• int r, l, b;
• cout << “Enter the Value of r, l & b: ”;
• cin>>r>>l>>b;
• cout<< “Area of circle is ”<<area(r)<<endl;
• cout<< “Area of rectangle is ”<<area(l,b); }
• float area(int a) {
• return (3.14*a*a); }
• int area(int a, int b) {
• return (a*b); }
Tuesday, December 24, 2024 Abdela A. 60

You might also like