Function and Recursion (28 November 2018)
Modular Programming
Program can be divided into many modules using function which is formed by grouping some statements to do a particular job. This also called as Sub-Program.
Using modules give advantages such as
Program can be divided into many modules using function which is formed by grouping some statements to do a particular job. This also called as Sub-Program.
Using modules give advantages such as
- Can divide huge program into smaller modules
- Easier to debug
- Can modify it without affecting overall codes
- Easier to document
- Library function = Standard function provided by C compiler.
Example : printf() in stdio.h, pow() in math.h - User-defined function = Self defined functions created by the user.
How functions looks like?
return-value-type function-name(parameter-list){
statements;
}
- return-value-type : Data type of the value returned.
If not filled it will use the default data type. If it's void it will not return any value. - parameter-list : List of value sent from the user.
Function usually written above the main program. Otherwise should use Function Prototype to ensure a function is know by the intiatior/caller and to make the compiler validating the parameters. Function Prototype can be written as
int max(int a, int b);
Indetifier Scoping
Divided into two :
- Local Identifier
Declared in a function including the parameters. The scope limited in the function. - Global Indetifier
Declared outside any function and placed on top of all function in the program. It can be reached from any point in the program.
Passing Parameter
If a module is not self sufficed then it need data or value and its result passes in and out using parameter. Passing Parameter divided into 2 :
- By-Value : Sent to other module is the value
- By Location/Reference : Sent to other module is the address
Passing Parameter also can be 1D Array and 2D Array.
Recursive
A function call inside a certain function calling itself.
Recursive function has 2 components:
- Base Case : Return value(constant) without calling next recursive call.
- Reduction step : Sequence of input converging to the base case.
Example :
Base Case : n = 0
Reduction step = f(n) = n * f(n-1)
Recursive have disadvantages such as using more memory because it stacking the memory and it takes longer time because need to traverse through all recursive call using stack.
Komentar
Posting Komentar