Fuction & Recursion
Function and Recursion
Modular Programming (also called Sub-Program)
- Module in C programming language is implented using function.
- Function is formed through grouping some statements to do a particular job.
- Module is needed when a certain block of statement frequently used by other distict in a program.
Advantages of using modules :
- Top-down design with sub goal, huge program divided into smaller modules.
- Can be done by more than one programmer.
- Easier to debug (easier to pin point errors and easy to follow).
- Modification can be done without effecting overall codes.
- Easier to document.
Best practice in module programming :
- High Fan-In
- Low Fan-out
- Self-Contained
Library vs User-Defined Function
Function in C divided in two types : Library fuction and User-defined function.
Library Function is a standard function provided by C compiler. Those function described in the header files.
User-defined fuctions is a sel defined functions.
Function Construction
return-value-type function-name( parameter-list )
{
statements;
statements;
}
return-value-type : data type of the value returned
if return-value-type is void then the fuction will not return value
if not filled, then default data type will be used
parameter-list : list of value sent from the user
Function Prototype
Function prototype objective : to ensure a function is known by the caller and compiler will validate the parameters
syntax :
return-value-type fuction-name (parameter-list);
Function prototype can also be written : int maximum (int a, int b);
Identifier Scoping
scope of identifier is reachable.
- Local
Declared in a function.
Scope limited in function.
- Global
Declared outside any function.
Can be re-declared in subprogram.
Reachable from any point in the program.
It is advisable not use global varable for :
- Error rate might increase
- Difficlut in debugging
- All functions in the program can change its value.
Passing Parameter
- By-Value : the value is sent to other module
- By Location/reference : the address is sent to other module
Recrusive Definition
Recrusive is a function call inside a certain function calling itself. For recursive problem.
Recrusive function has two components :
~ Base case : return value(constant) without calling next recrusive call.
~ Reduction step : sequence of input value converging to the base case.
Recrusive
Needs :
~ More memory consumption
~ Takes longer time
Generally, use recrusive solution if :
- Difficult to solve iteralitvely.
- Efficiency using recrusive has been reached.
- Efficiency is less important in comparison with readability.
- Memory efficiency and execution time are not the main concern.
Comments
Post a Comment