0% found this document useful (0 votes)
61 views26 pages

Chapter 5

This document discusses functions in C++. It defines a function as a block of code that performs a specific task and can be called from different parts of a program. Functions make programs easier to write, read, debug and maintain by breaking problems into smaller, modular pieces. The key aspects covered include: - Function definition syntax including return type, name, parameters and body - Calling and defining functions - Scope of variables as local, parameters or global - Passing arguments by value vs reference to allow modifying external variables - Default values for parameters

Uploaded by

yohans shegaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views26 pages

Chapter 5

This document discusses functions in C++. It defines a function as a block of code that performs a specific task and can be called from different parts of a program. Functions make programs easier to write, read, debug and maintain by breaking problems into smaller, modular pieces. The key aspects covered include: - Function definition syntax including return type, name, parameters and body - Calling and defining functions - Scope of variables as local, parameters or global - Passing arguments by value vs reference to allow modifying external variables - Default values for parameters

Uploaded by

yohans shegaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter 5

FUNCTION
Function

 Computer programs that solve real-world problems are


usually much larger than the simple programs discussed
so far.
To design, implement and maintain larger programs it is
necessary to break them down into smaller, more
manageable pieces or module
Dividing the problem into parts and building the solution
from simpler parts is a key concept in problem solving
and programming.
 In C++ we can subdivide the functional features of a
program into blocks of code known as functions.
 a function is a block of instructions that is executed
when it is called from some point of the program.
 Until now you have encountered programs where all the
code (statements) has been written inside a single
function called main ().
 Every executable C++ program has at least this function.
In the next sections we will learn how to write additional
functions.
Advantages of using function are:
 Easy to write a correct small function
 Easy to read, write, and debug a function
 Easier to maintain or modify the program written using
function
 Small self reliable functions tend to be self documenting
and highly readable
 It can be called any number of times in many place with
different parameter
5.1 Function definition
The following is format of function is called function
definition:

type name ( parameter1, parameter2, ...)


{
body of the function
.
.
.
return something;
}
type: is the data type specifier of the data returned by the
function.
name: is the identifier/name by which it will be possible
to call the function.
Parameter: (as many as needed): Each parameter consists
of a data type specifier followed by an identifier, like any
regular variable declaration (for example: int x) and
which acts within the function as a regular local variable.
Parameters pass arguments to the function when it is called. The
different parameters are separated by commas.
body of the function: It is a block of statements surrounded by
braces { }.
return: is value returned at the end of the execution of the
function to the caller function.
// function example
#include<iostream.h> Output
//function definition
int addition (int a, int b)

{
int r;
r=a+b;
return r;
}
int main () // main function
{
int z;
z = addition (5, 3);
cout << "The result is: " << z;
return 0;
}
 A C++ program always begins its execution by the main
function. So this program starts its execution from there.
We can see how the main function begins by declaring the
variable z of type int.
 Right after that, we see a call to a function called
addition.
 similarity between the structure of the call to the function
and the declaration of the function itself
 Within the main function we called to addition passing two values:
5 and 3, that correspond to the int a and int b parameters declared for
function addition.
At the point at which the function is called from within main (), the
control is lost by main and passed to function addition.
Function addition declares another local variable (int r), and by
means of the expression r=a+b, it assigns to r the result of a plus b.
Because the actual parameters passed for a and b are 5 and 3
respectively, the result is 8.
return r; finalizes function addition,
 the call to a function (addition (5, 3)) is literally replaced
by the value it returns (8).
cout << "The result is:" << z;
That, as you may already expect, produces the printing of
the result on the screen.
Declaring functions
This declaration is shorter than the entire definition, but significant
enough for the compiler to determine its return type and the types
of its parameters.
type name ( argument_type1, argument_type2, ...);
It is identical to a function definition, except that it does not
include the body of the function itself (i.e., the function statements
that in normal definitions are enclosed in braces ({}) and instead of
that we end the prototype declaration with a mandatory semicolon
(;).
For example, we can declare a function called protofunction with
two int parameters with any of the following declarations:
int protofunction (int first, int second); or
int protofunction (int, int);
//declaring functions prototypes
#include <iostream.h>
void odd (int a);
void even (int a);
int main ()
{
int i;
cout << "Type any number to check and 0 to exit: ";
cin >> i;
while(i)
{
odd (i);
cout << "Type any number to check and 0 to exit: ";
cin >> i;
}
cout<<"Thank you for using this application!\n";
return 0;
}
void odd (int a)
{

if ((a%2)!=0) cout << "Number is odd.\n";


else
even (a);
}
void even (int a)
{
if ((a%2)==0) cout << "Number is even.\n";
else odd (a);
}
5.2 Scope of variables
 the scope rules determine what code has access to a variable
The scope rules also determine the lifetime of a variable.
There are three types of variables: local variables, formal
parameters, and global variables.
1. Local variables- declared inside a function
The scope of variables declared within a function or any other inner
block is only in their own function or in their own blocks and cannot
be used outside of them.
For example, in the previous example it would have been
impossible to use the variables a, b or r directly in function main
since they were variables local to function addition.
 Declaring Variables within Iteration and Selection
Statements
It is possible to declare a variable within the initialization
portion of a for loop or the conditional expression of an if,
switch, or while.
A variable declared in one of these places has its scope
limited to the block of code controlled by that statement.
A local variable will not hold its value between
activations.
For example, a variable declared within a for statement
will be local to that loop, as the following example shows.
#include <iostream>
using namespace std;
int main()
{
// i is local to for loop only
for(int i = 0; i<10; i++)
{
cout << i << " ";
cout << "squared is " << i * i << "\n";
}
//i = 10; // *** Error *** -- i not known here!
return 0;
}
1. Formal Parameters
As you know, if a function uses arguments, then it must declare
variables that will accept the values of those arguments.
 These variables are called the formal parameters of the function.
Aside from receiving the arguments when a function is called,
formal parameters behave like any other local variables inside the
function
 The scope of a parameter is local to its function.
3. Global variable
Global variables are, in many ways, the opposite of local variables.
They are known throughout the entire program, can be used by any
piece of code, and maintain their values during the entire execution
of the program.
Therefore, their scope extends to the entire program. You can create
global variables by declaring them outside of any function.
#include<iostream>
using namespace std;
const float pi=3.14; //global variable
 float sphereArea(float r); /*function prototype, Note that parameter has identifier*/
float sphereVolume(float);/*function prototype, note that parameters have no identifiers*/
int main()
{
float radius;// local variable
float result;// local variable
cout<<"please enter the radius: ";
cin>>radius;
result=sphereArea(radius);
cout<<"\n The area of sphere= "<<result;
result=sphereVolume(radius);
cout<<"\n The volume of sphere= "<<result;
}
  float sphereArea(float r)//function definition, with formal parameter< float r>
{
float A;// local variable
A=4*pi*r*r;
return A;
}
float sphereVolume(float r)//function definition, with formal parameter< float r>
{
float V;// local variable
V=4*pi*r*r*r/3;
return V; }
Functions with no type
If no return value is required
// void function example
#include <iostream>
using namespace std;
void printmessage ()
{
cout << "I'm a function!";
}
int main ()
{
printmessage ();
return 0;
}
5.3. Arguments passed by value and by reference
Until now, in all the functions we have seen, the
arguments passed to the functions have been passed by
value.
This means that when calling a function with parameters,
what we have passed to the function were copies of their
values but never the variables themselves. For example,
suppose that we called our first function addition using the
following code:
int x=5, y=3, z;
z = addition ( x , y );
 there might be some cases where you need to manipulate from inside a function
the value of an external variable.
For that purpose we can use arguments passed by reference, as in the function
duplicate of the following example:
// passing parameters by reference
#include <iostream>
void duplicate (int& a, int& b, int& c)
{
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;}
// more than one returning value
#include <iostream>
void prevnext (int x, int& prev, int& next) {
prev = x-1;
next = x+1;
}
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}
5.4. 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. For example:
// default values in functions
#include <iostream>
int divide (int a, int b=2)
{ int r;
r=a/b;
return (r);
}
int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}
5.5. Overloaded function
In C++ two different functions can have the same name if
their parameter types or number are different. That means
that you can give the same name to more than one function
if they have either a different number of parameters or
different types in their parameters. For example:
// overloaded function
 #include <iostream>
int operate (int a, int b)
{
return (a*b);
}
float operate (float a, float b)
{
return (a/b);
}
int main ( )
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
}

You might also like