0% found this document useful (0 votes)
36 views34 pages

Chapter 5

Chapter Five discusses modular programming, emphasizing the importance of breaking down programs into smaller, manageable functions in C++. It covers function declaration, definition, scope, storage classes, and the concept of recursion, along with examples of parameter passing and function overloading. The chapter highlights the benefits of modularity, such as easier testing and maintenance of code.

Uploaded by

abdatadalacha5
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)
36 views34 pages

Chapter 5

Chapter Five discusses modular programming, emphasizing the importance of breaking down programs into smaller, manageable functions in C++. It covers function declaration, definition, scope, storage classes, and the concept of recursion, along with examples of parameter passing and function overloading. The chapter highlights the benefits of modularity, such as easier testing and maintenance of code.

Uploaded by

abdatadalacha5
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/ 34

Chapter Five

Modular Programming
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)
Functions in C++
• Modules in C++ are called functions
• Function - a subprogram that can act on data
and return a value
• Every C++ program has at least one function,
main(), where program execution begins
• A C++ program might contain more than one
function.
• Functions may interact using function call
• Functions in C++ come in two varieties:

– user-defined

– built-in
• E.g pow(), sqrt(), cin, etc
Declaration of Functions
• Functions must be declared before use
• The declaration tells the compiler
– The name,
– Return type,
– Parameters of the function
• Three ways
– Write your prototype into a file, and then use the #in-
clude directive to include it in your program.
– Write the prototype into the file in which your function
is used.
– Define the function before it is called by any other
function.
Function Prototypes
• The declaration of a function is called its pro-
totype
• Is a statement - it ends with a semicolon
• It consists of the function's
– return type,
– name,
– parameter list
• Syntax
– return_type function_name (type [parameter-
Name1], type [ParameterName2] ... );
• E.g. long Area(int, int);
Or
long Area(int length, int width);
Function Prototypes
• All functions have a return type – default is int
• If the function doesn’t have a return type void
will be used
– void is a reserved word
• The function prototype usually placed at the
beginning of the program
• The definition of the prototype must be given
• Many of the built-in functions have their func-
tion prototypes already written in the header
files you include in your program by using #in-
clude
Defining a Function
• The definition tells the compiler how the function
works.
• Consists of :
– the function header :
• like the function prototype except that the parameters must be
named
• there is no terminating semicolon
– its body
• the task of the function
• Syntax
return_type function_name(parameter
declarations)
{
declarations;
statements;
}
Defining a Function
• E.g.
long Area(long l, long w)
{
return l * w;
}
• The return statement without any value is
typically used to exit the function early
• C++ does not allow nested functions
– The definition of one function cannot be in-
cluded in the body of another function
• A function definition must agree in return
type and parameter list with its prototype
Defining a Function
• If the function returns a value, it’s definition
should end with a return statement
• The body of the function is always enclosed in
braces, even when it consists of only one state-
ment
• return keyword
– Returns data, and control goes to function’s
caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies data types
int square( int ); // function prototype of arguments and return values.
square expects an int, and returns
int main() an int.
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call

cout << endl; Parentheses () cause function to be called.


When done, it returns the result.
return 0; // indicates successful termination

} // end main

// square function definition returns square of an integer


int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
Definition of square. y is a
copy of the argument passed.
} // end function square Returns y * y, or y squared.

1 4 9 16 25 36 49 64 81 100
Scope of identifier
• Refers to where in the program an identifier
is accessible
• Determines how long it is available to your
program and where it can be accessed
• Two kind
– Local identifier - identifiers declared within a
function (or block).
– Global identifier – identifiers declared outside
of every function definition.
Local scope
• You can declare variables within the body of the
function
– local variables
– When the function returns, the local variables are no
longer available
• Variables declared within a block are scoped to
that block – Local to that block
– they can be accessed only within that block and "go
out of existence" when that block ends
– E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
Global Scope
• Variables defined outside of any function
have global scope
• Available from any function in the program,
including main()
• A local variable with the same name as a
global variable hides the global variable -
when used within the function
Global/Local Example
int count(0);// global
...
int main()
{
int x, y, z; //local
...
}
int calc(int a, int b)
{
int x;
count += x; // global
...
}
Unary Scope Resolution Opera-
tor ::
• Using ::, one can access an global variable even
if it is over-shadowed by a local variable of the
same name.
• E.g.
#include <iostream.h>
float num=10.8;
int main(){
float num= 9.66;
cout<<the value of num is:<<::num<<endl;
return 0;
}
inline Functions
• Function calls
– Cause execution-time overhead
• Qualifier inline before function return type "ad-
vises" a function to be inlined
• Puts copy of function's code in place of function call
– Speeds up performance but increases file size
– Compiler can ignore the inline qualifier
• Ignores all but the smallest functions
– E.g.
inline double cube( const double s )
{
return s * s * s;
}
inline functions
• Advantage: function call overhead is elim-
inated, thus faster and less memory con-
suming
• Disadvantage: the code is expanded dur-
ing compilation so that executable file is
large
Storage class
• Storage class determines the period during which an
identifier exists in memory
• Four storage classes
– auto
• Local variables in functions or blocks. Auto storage class variables
are created only when the block is active, and disappear when the
block or function exits.
– register
• Variable existence like auto. The register variable is a suggestion to
the compiler to put the variable in a CPU register.
– static
• Local static variable exists during the whole program executing, i.e.,
the variable retains its value between function calls.
– extern
• Global variables and function names have the storage class extern.
Extern storage class variable exists during the whole program exe-
cution.
Storage class and variables
• Automatic variable - memory is allocated at
block entry and deallocated at block exit
• Static variable - memory remains allocated as
long as the program executes
– Retain their values across function calls.
• Variables declared outside of any block are
static variables
• By default, variables declared within a block are
automatic variables
• Declare a static variable within a block by using
the reserved word static
Static and Automatic Variables
(continued)
• The syntax for declaring a static variable is:
static dataType identifier;
– E.g.
static int x;
– declares x to be a static variable of the type int
• Static variables declared within a block are local
to the block
• Their scope is the same as any other local iden-
tifier of that block
Storage Class and Scope
• Local Objects
– Defined within a function
– Can be accessed only within the function
– Automatic storage class (default)
– Static storage class (retained entire execu-
tion)
• Global Objects
– Defined outside all functions
– Can be accessed by any function
– External storage class
Functions with Default Parameters
• When a function is called
– The number of actual and formal parameters
must be the same
• C++ relaxes this condition for functions with
default parameters
• You specify the value of a default parame-
ter when the function name appears for the
first time, such as in the prototype
Functions with Default Parameters
(continued)
• If you do not specify the value of a default parameter
– The default value is used
• All of the default parameters must be the rightmost pa-
rameters of the function
• In a function call where the function has more than one
default parameter and a value to a default parameter is
not specified
– You must omit all of the arguments to its right
• Default values can be constants, global variables, or
function calls
• The caller has the option of specifying a value other than
the default for any default parameter
• You cannot assign a constant value as a default value to
a reference parameter
Empty Parameter Lists
• functions can take no arguments
• To declare that a function takes no parame-
ters:
– Write void or nothing in parentheses
• E.g
– void print1( void );
– void print2();
Parameter Passing
• Call by Value
– Value of the function argument passed to the
formal parameter of the function
– Copy of data passed to function
– Changes to copy do not change original
• Call by Reference
– Address of the function argument passed to the
formal parameter of the function
Call by Reference
• Reference parameters are useful in three
situations:
– Returning more than one value
– Changing the actual parameter
– When passing the address would save mem-
ory space and time
Call by Value Example
/* Incorrect function to switch two values */

void swap(int a, int b)


{
int hold;

hold = a;
a = b;
b = hold;

return;
}
Call by Reference Example
/* Correct function to switch two values */

void swap2(int& a, int& b)


{
int hold;

hold = a;
a = b;
b = hold;

return;
}
Recursion and Recursive Functions

• Main calls another function…..normal


• A function calls another function2….normal
• A function calls itself ?! Possible?? YES
A recursive function is one that call itself.
Concept Of recursion
• A function can also call itself, this is known as recursion
• To avoid infinite recursion, one must have a terminating condi-
tion in the function
• A recursive function is called to solve a problem
• The function knows to solve only the simplest cases or so-
called base-cases.
• The function keeps dividing each new sub problem into two
conceptual pieces until eventually terminates after converging
on the base-case.
• The function thus recognize the base-case and returns a result
to the previous copy of the way up the line until original call
of the function returns the final result to main.
Finding Factorial Recursively
5! 5! Final value=120
5!=5*24=120 returned
5*4! 5*4!
4!=4*6=24 returned
4*3!
4*3!
3!=3*2=6 returned
3*2! 3*2!
2!=2*1=2 returned
2*1! 2*1!
1
1
1
Finding Factorial iteratively
#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is:
"<<fact<<endl;
return 0;
}
Function Overloading
• Function overloading
– Functions with same name and different param-
eters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
• A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters

You might also like