Function
So, program is divided into modules. The modules in C programming language are execute using function. Function is a group of sentence that does a specific job.
Function in C usually written above the int main()
The benefit of using Function :
1. A huge program can be divide into smaller modules.
2. Easier to fix if there is a problem.
3. Easier to document
return_type_value function_name ( parameter-list )Function Construction :
{
statement;
}
return-value-type : data type of the value returned,
- If not filled, then default data type will be used (integer)
- If return-value-type is void then the function will not return value
example :
int maximum (int a,int b )
{
statement
}
int : return value type of integer
int a, int b : the parameter input by user
statement : all the task that function needs to do
Passing Parameter : If a module is not self sufficed then needed data/value and its result passes in and out using parameter(s)
Sending parameter can be by two ways :
1. by value, is when you sent the value to the other module
2. by location / reference, is by using array one dimension or two dimension
--------------------------------------------------------------------------------
Recursive
Is a function call, inside a certain function calling itself. And also recursive can be combined with function.
Example :
1. A recursive function to find a factorial n.
2. A recursive function to find a Fibonacci sequence
When Making A Recursive, Recursive Function has two components :
- Base Case : return value(constant) without calling next recursive call.- Reduction step : sequence of input value converging to the base case.
Example:
(Factorial function)
Base case : n = 0
Reduction step: f(n) = n * f(n-1)
The Bad Thing About using Recursive
- More memory consumption.- Takes longer time, should traverse through all recursive call using stack
Generally, use recursive solution if:
- Difficult to solve iteratively.- Efficiency is less important in comparison with readability
- Memory efficiency and execution time are not the main concern. ( Consider carefully speed and efficiency using iterative approach, rather than nice logical design using recursive )
Comments
Post a Comment