Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

Chapter 4

Functions

1
Modular programming
 Modular programming is breaking down the design of a program into individual components
(modules) that can be programmed and tested independently

 It is a requirement for

 Effective development

 Maintenance of large programs and projects

 Procedures of a common functionality are grouped together into separate modules.

 Program is now divided into several smaller parts which interact and which form the whole
program.
Function
 Modules in C++ are called functions

 A function is a block of code designed to tackle a specific problem.

 A function is a subprogram that can act on data and return a value.

 Every C++ program has at least one function, main()

 Each function has its own name, and when that name is encountered, the execution of the program
branches to the body of that function.

 Functions come in two varieties


1. User defined
2. Built-in

 Built-in functions are part of your compiler package--they are supplied by the manufacturer for your
use
Basics of Function
 One of the best ways to tackle a problem is to start with the overall goal, then divide this goal
into several smaller tasks.

 You should never lose sight of the overall goal, but think also of how individual pieces can fit
together to accomplish such a goal.

 If your program does a lot, break it into several functions.

 Each function should do only one primary task.


Cont’d…
 C++ functions generally adhere to the following rules

1. Every function must have a name

2. Function names are made up and assigned by the programmer following the same rules
that apply to naming variables.
 They can contain up to 32 characters, they must begin with a letter, and

 They can consist of letters, numbers, and the underscore (_) character.

3. All function names have one set of parenthesis immediately following them.

4. The body of each function, starting immediately after parenthesis of the function name,
must be enclosed by braces
Declaring function
 The interface of a function (also called its prototype) specifies how it may be used

 It consists of three entities:

 The function return type. This specifies the type of value the function returns. A
function which returns nothing should have a return type void.
 The function name: this is simply a unique identifier

 The function parameters (also called its signature). This is a set of zero or more typed
identifiers used for passing values to and from the function.
Cont’d…
 Prototype syntax:

return_type function_name ( [type [parametername1] ,type [parametername2]]...);

 e.g.

long Area(int, int); or

long Area(int length, int width);


Defining the function
 A function definition consists of two parts: interface (prototype) & body.

 The brace of a function contains the computational steps (statements) that computerize the
function.

 The definition consists of a line called the decelerator.


Cont’d…
 If function definition is done before the main function, then there is no need to put the
prototype, otherwise the prototype should be scripted before the main function starts.

 Using a function involves ‘calling’ it

 Calling a function means making the instruction of the function to be executed.

 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 and type of arguments should match the number of function parameters
Cont’d…
 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 return value (if any) is passed to the caller.

 A function call in C++ is like a detour on a highway.

 Imagine that you are traveling along the “road” of the primary function called main()

 When you run into a function-calling statement, you must temporarily leave the main()
function and execute the function that was called.
Cont’d…
Cont’d…
void func1();  prototype of function
void main()
{
Func1();  Function Call
}
void func1()  No semicolon. Decelerator
{
-------------- Function body definition
--------------
}
Cont’d…
#include<iostream.h>
#include<conio.h>
void starline(); // prototype of the function with a name starline
int main()
{
starline(); // calling the function with a name starline
cout<< “Department” << endl;
starline();
cout<< “Software Engineering” <<endl
<< “CS” <<endl
<< “Accounting” <<endl
<< “ management” <<endl
<< “IT” << endl;
starline();
return 0;
}
Cont’d…
void starline() //definition of the function with a name starline
{
for(int j=0;j<45;j++)
cout<< “*”;
cout<<endl;
} Output:

*********************************************
Department
*********************************************
Software Engineering
CS
Accounting
management
IT
*********************************************
Function parameters and arguments
 The parameters of a function are list of variables used by the function to perform its task

 The arguments passed to the function during calling of a function are values sent to the
function

 The arguments of function calling can be using either of the two

1) Passing by Value

2) Passing by Reference
Passing by Value
 A value parameter receives a copy of only the value of the argument passed to it.
 As a result, if the function makes any changes to the parameters, this will not affect the
argument.
 For instance:
#...
void Foo(int num)
{
num = 0;
cout<< “num = ” << num << “ \n”;
}
int main()
{
int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
return 0;
}
Cont’d…
 The single parameter of Foo 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 passed to it, num receives a copy of the value of x.

 As a result, although num is set to 0 by the function, this does not affect x.

Output

Num = 0

x = 10
Passing by Reference
 A reference parameter, on the other hand, receives the argument passed to it and works on it
directly.
 Any change made by the function to a reference parameter is in effect directly applied to the
argument.
 Passing parameters in this way is called pass-by-reference
E.g. void Foo(int & num)
{
num = 0;
cout<< “num = ” << num << “ \n”;
}
int main()
{
int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
return 0;
}
Cont’d…
The parameter of Foo is a reference parameter.
 num will correspond to x for this specific program as it x is sent by its reference and
not its value.
Any change made on num will be effected to x.
Output
num=0
x=0

19
Scope of variables
 A variable has scope, which determines how long it is available to your program and where it
can be accessed

1. Local variables

2. Global variables

 Local variables: Not only can you pass in variables to the function, but you also can declare
variables within the body of the function.
 This can be done by Local variables

 So named because they exist only locally within the function itself
Cont’d…
#include <iostream.h>
float convert(float);
int main()
{
float tempfer;
float tempcel;
cout << "please enter the temperature in fahrenheit: ";
cin >> tempfer;
tempcel = convert(tempfer);
cout << "\nhere's the temperature in celsius: ";
cout << tempcel << endl;
return 0;
}
float convert(float tfer) {
float tcel;
tcel = ((tfer - 32) * 5) / 9;
return tcel; }
Global Variables
 Variables defined outside of any function have global scope and thus are available from any
function in the program, including main()

 Local variables with the same name as global variables do not change the global variables

 A local variable with the same name as a global variable hides the global variable,

 However. If a function has a variable with the same name as a global variable, the name refers
to the local variable--not the global--when used within the function.
Cont’d…
#include <iostream.h>
void myfunction(); // prototype
int x = 5, y = 7; // global variables
int main() Output:
{ x from main: 5
cout << "x from main: " << x << "\n"; y from main: 7
cout << "y from main: " << y << "\n\n";
x from myfunction: 15
myfunction();
y from myfunction: 10
cout << "back from myfunction!\n\n";
cout << "x from main: " << x << "\n"; back from myfunction!
cout << "y from main: " << y << "\n";
return 0; x from main: 5
} y from main: 7
void myfunction()
{
int x=15,y = 10;
cout << "x from myfunction: " << x << "\n";
cout << "y from myfunction: " << y << "\n\n"; }
Scope operator
 Because a local scope overrides the global scope, having a local variable with the same name
as a global variable makes the latter inaccessible to the local scope.
 E.g.
int num1;
void fun1(int num1)
{
//…
} `
The global num1 is inaccessible inside fun1(), because it is overridden
by the local num1 parameter.
Cont’d…
 This problem is overcome using the scope operator ‘::’ which takes a global entity as
argument.
int num1 = 2;
void fun1(int num1)
Output:
{
33
//… 2
num1=33;
cout<<num1;
cout<<::num1;
if(::num1 != 0)
//…
}
Automatic vs Static variables
 The terms automatic and static describe what happens to local variables when a function
returns to the calling procedure.
 By default, all local variables are automatic, meaning that they are erased when their function
ends.
 You can designate a variable as automatic by prefixing its definition with the term auto.
E.g.
main()
{
int I;
auto float x;
}
Cont’d…
 The opposite of an automatic is a static variable.
 All global variables are static and, as mentioned, all static variables retain their values.
 Therefore, if a local variable is static, it too retains its value when its function ends-in case this
function is called a second time
 To declare a variable as static, place the static keyword in front of the variable when you define
it.
 If static variables are not declared explicitly, they will be declared to 0 automatically.
Cont’d…
 E.g.
void my_fun()
{
static int num;
static int count = 2;
count=count*5;
num=num+4;
}
 During the first call of the function my_fun(), the static variable count will be
initialized to 2 and will be multiplied by 5 at line three to have the value 10.
 During the second call of the same function count will have 10 and will be multiplied by 5.
Cont’d…
 During the first call of the function my_fun(), the static variable num will be initialized to 0 (as
it is not explicitly initialized) and 4 will be added to it at line four to have the value 4.

 During the second call of the same function num will have 4 and 4 will be add to it again.
Inline function
 If a function is declared with the keyword inline, the compiler does not create a real function:
 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.
Syntax
inline return_type function_name ( [type parameterName1], [type parameterName2]...)
{
statements;
}
Inline function
inline int Double(int);
int main()
{
int target;
cout << "Enter a number to work with: ";
cin >> target;
cout << "\n";
target = Double(target);
cout << "Target: " << target << endl;
target = Double(target);
cout << "Target: " << target << endl;
target = Double(target);
cout << "Target: " << target << endl;
return 0;
}
Inline function
int Double(int target)
{
return 2*target;
}

Output: Enter a number to work with: 20

Target: 40
Target: 80
Target: 160
Default arguments
 Default argument is a programming convenience which removes the burden of having to
specify argument values for all function parameters . E.g.
 You might pass a function an error message that is stored in a character array, and the function
displays the error for a certain period of time.
 The prototype for such a function can be this:
Void pr_msg(char note[]);
 Therefore, to request that pr_msg() display the line ‘Turn printer on’, you call it this way:
Pr_msg(“Turn printer on”);
 As you write more of the program, you begin to realize that you are displaying one message-for
instance, the ‘Turn printer on’ msg more often than any other message.
Cont’d…
 Instead of calling the function over and over, typing the same message each time, you can set
up the prototype for pr_msg()
 So that it defaults to the ‘turn printer on’ message in this way:
Void pr_msg(char note[] = “Turn printr on”);
 E.g.
#include…..
void Add_Display(int x=10, int y=20, int z=30)
{
cout<< (x+y+z);
}
void Mult_Dispaly (int x, int y=70)
{
cout<< (x*y);
}
Cont’d…
int main()
{
int a=40, b=50, c=60;
Add_Display(a,b,c);
Add_Display(a,b);
Add_Display(a);
Add_Display();
Mult_Display(a,b)
Mult_Display(a)
Mult_Display()
return 0;
}
Cont’d…
Output
150
120
90
60
2000
2800
Error
Overloaded functions
 Unlike C, C++ lets you have more than one function with the same name.
 Functions with the same name are called overloaded functions.
 C++ requires that each overloaded functions differ in its argument list
 Overloaded functions enable you to have similar functions that work on different types of data.
e.g.
int abs(int i);
float abs(float x);
Recursive Functions
 Most mathematical functions that we are familiar with are described by a simple formula.
 For example, we can convert temperatures from Fahrenheit to Celsius by applying the formula
C = 5 (F-32) / 9
 A function that is defined in terms of it self is called recursive
 When writing recursive routines, it is crucial to keep in mind the four basic rules of recursion.
 These are:
1) Base case: you must always have some Base case, which can be solved with out recursion
2) Making progress: for the cases that are to be solved recursively, the recursive call must
always be to a case that makes progress to ward a base case
3) Design rule: Assume that all recursive calls work without fail.
4) Compound interest rule: never duplicate work by solving the same instance of a problem
in separate recursive rule.
Cont’d…
Example
 Factorial function f(n)= n!
 F(n)=n*(n-1)*(n-2)*(n-3)*…*1 this is iterative definition
 This function can be implemented both iteratively or recursively as
//iterative implementation
int factorial (int N)
{
int fact =1;
for(int i=1;i<=n; i++)
{
fact *= i;
}
return fact;
}
Cont’d…
//recursive implementation
int factorial (int n)
{
if (n == 0) return 1;
return n*factorial(n-1)
}
Thank You!

You might also like