PPT06-Function and Recursion

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

Course : Algorithm and Programming

Effective Period : 2022

TOPIC 06

FUNCTION AND RECURSION


LEARNING OUTCOME

At the end of this session, the student will be able to:


• LO 2: Analyze a program using C language for problem-solving
OUTLINE

• Modular Programming
• Function
• Identifier Scoping
• Passing Parameter
• Recursion
MODULAR PROGRAMMING

o Program is divided into modules


o Module in C programming language is implemented using function
o Function is formed through grouping some statements to do a particular job
o Module is needed when a certain block of statement frequently used by other distinct code in a
program
o Also called Sub-Program
MODULAR PROGRAMMING

o Advantages of using Modules:


1. Top-down design with sub goal, huge program divided into smaller modules
2. Can be done by more than one developer/ programmer
3. Easier to debug, as logical flow is easy to follow and easier to pin point errors
4. Modification can be done without affecting overall codes
5. Easier to document
MODULAR PROGRAMMING

o C programming language implements modular programming using function


o Example of dividing program into subprograms

Main Program

SubProgram SubProgram SubProgram

SubProgram SubProgram
MODULAR PROGRAMMING

o Best practice in module programming:


• High Fan-In, frequently used
• Low Fan-Out, more specific functionality/ small number of job
• Self-Contained, self resource sufficient
LIBRARY VS USER-DEFINED
FUNCTION
o Function in C divided in two types :
• Library function
• User-defined function
o Library function, is a standard function provided by C compiler. Those function described in
the header files (.h)
Example: strcpy() in string.h
sqrt() in math.h
printf() in stdio.h
o User-defined function is self defined functions
LIBRARY VS USER-DEFINED
FUNCTION
Example:
Program using Standard Library Function : printf and sqrt

#include<stdio.h>
#include<math.h>
int main() {
int i;
for(i=0; i<6; i++)
printf(“%d %f”,i,sqrt(i));
return 0;
}
FUNCTION DEFINITION

Function Construction

return-value-type function-name( parameter-list )


{
statements;
}

return-value-type: data type of the value returned


If not filled, then default data type will be used (default integer)
If return-value-type is void then the function will not return value

Parameter-list: list of value sent from the function initiator (user)


FUNCTION DEFINITION

• Example : Formal parameter

int maximum (int x, int y){ Function


int max = x;
if ( y > max) max = y;
return max
Initiator/ Caller
}

void main () {
int a,b;
printf("Input 2 even values : ");
scanf("%d %d", &a, &b);
printf("Largest value is : %d\n",maximum(a,b));
}

Actual parameter
FUNCTION DEFINITION

Function in C usually written above the initiator/caller or main program. Otherwise, should use
Function Prototype

Function Prototype Objective:


To ensure a function is known by the initiator/caller
Compiler will validate the parameters

Syntax :
return-value-type function-name ( parameter-list );
FUNCTION PROTOTYPE

o Example:

#include <stdio.h> No need for function


prototype as the
int maximum (int x, int y){ function placed
int max = x; above initiator (main
if ( y > max) max = y; program)
return max
}

void main () {
int a,b;
printf("Input 2 even values : ");
scanf("%d %d", &a, &b);
printf("Largest value : %d\n",maximum(a,b));
}
FUNCTION PROTOTYPE

Function Prototype can be written as follows:

int maximum (int a, int b);

Important:
parameters data type, number of parameters and its order
IDENTIFIER SCOPING

Identifier Scoping:
scope of an identifier is reachable

Identifier Scoping:
• Local
• Global
IDENTIFIER SCOPING

o Local Identifier
• Identifier declared in a function including the parameters
• Scope limited in the function
o Global Identifier
• Identifier declared outside any function and placed on top of all functions in a C program
• Reachable from any point in the program
• Global Identifier, can be re-declared in subprogram
• It is advisable not to use global variable for the following reasons:
– Error rate might increase as line of code increase.
– Difficult in debugging
– Exclusivity of data is low. All functions in the program can change its value
IDENTIFIER SCOPING

int x;
function1(){
scope of variable x
-
}
int y;
function2(){
int z;
- scope of variable y
}
main(){
int z;
int y;
- z and y scope only in main program
} z in main different from function2()
PASSING PARAMETER

o If a module is not self sufficed, then the needed data/value and its result passes in and out
using a parameter(s)
o List of parameters is the interface of a module with other modules
o Passing Parameter
– By-Value, sent to other module is the value
– By Location/by reference, sent to other module is the address
PASSING PARAMETER

o Example: (Passing Parameter by Value)


#include <stdio.h>
void Line (char x ) { /* x is Formal Parameter*/
{
int i; / *i, x are Local Variable */
for (i = 1; i<=10; i++) printf(“%c”,x);
}

/*Main Program*/
void main()
{
char A = ’-’;
Line(A); /* A is Actual Parameter */
}
PASSING PARAMETER

o Example: (Passing Parameter by Location)


#include <stdio.h>
void Calculate (int X, int Y, int *P, int *Q)
{
*P = X + Y;
*Q = X * Y;
}

void main()
{
int X, Y, P, Q; /*local variable*/
printf(“ X=”); scanf(“%d”,&X);
printf(“ Y=”); scanf(“%d”,&Y);
Calculate(X,Y,&P,&Q);
printf(”X + Y = %d\n”, P);
printf(”X * Y = %d\n”, Q);
}
RECURSIVE DEFINITION

• Recursive is a function call inside a certain function calling itself


• Recursive Function, suitable for recursive problem
• Example :
Factorial (n) or n! defined as follows :
n! = 1, for n = 0;
n! = n * (n-1)!, for n > 0
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1* 0!
0! = 1
Trace back : 4! = 1*2*3*4 = 24
RECURSIVE FUNCTION

o 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.

o Example: (Factorial function)


– Base case : n = 0
– Reduction step: f(n) = n * f(n-1)
ITERATIVE VS RECURSIVE

o Example: (Iterative vs Recursive)


• Factorial - Recursive
long factor (int n)
{
if(n==0) return (1);
else return(n * factor(n-1));
}

• Factorial - Iterative
long factor(int n) {
long i, fac = 1;
for(i=1; i<=n; i++) fac *= i;
return (fac);
}
RECURSIVE

Recursive Drawback
Although recursive code more concise it needs:
– More memory consumption – as stack memory is needed
– Takes longer time, should traverse through all recursive call using stack

Recursive Best Practice


Generally, use recursive solution if:
– Difficult to solve iteratively.
– Efficiency using recursive has been reached
– 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.
PROGRAM EXAMPLE USING
RECURSIVE
Fibonacci Number
sequence: 0, 1, 1, 2, 3, 5, 8, 13 ...
Relation between the number define recursively as follows:
Fib(N) = N if N = 0 or 1
Fib(N) = Fib(N-2) + Fib(N-1) if N >= 2

int Fib(int n) {
int f;
if(n==0) f = 0;
else if(n==1) f = 1;
else f = Fib(n-2) + Fib(n-1);
return f;
}
PROGRAM EXAMPLE USING
RECURSIVE
Fibonacci Number
Fibonacci illustration N=4

FIB (4)

FIB (3) FIB (2)

FIB (2) FIB (1) FIB (1) FIB (0)

FIB (1) FIB (0)


CLASSIC & MODERN
(FUNCTION PARAMETER
Classic Function Parameter Declaration DECLARATION)
int function1(a) #include <stdio.h>
int a;
{ int main()
a++; {
return a; int x;
} x=function1(3);
printf("x=%d\n",x);
int function2(b) x=function2(13);
int b; printf("x=%d\n",x);
{ return(0);
b = b * b; }
return b;
}
CLASSIC & MODERN
(FUNCTION PARAMETER
Modern Function Parameter Declaration DECLARATION)
int function1(int a) #include <stdio.h>
{
a++; int main()
return a; {
} int x;
x=function1(3);
int function2(int b) printf("x=%d\n",x);
{ x=function2(13);
b = b * b; printf("x=%d\n",x);
return b; return(0);
} }
SUMMARY

o In making good program design, modular programming is usually used. This concept is a
code to solve a problem into smaller parts (into modules). Function is a group of statements
used together to do the task. In program C has at least 1 main function, namely main (); And
in a program can make other functions besides the main function ();
o Function in the C language is divided into 2 groups, namely: Standard Library Function. and
programmer-defined function
o Identifier Scoping, based on its reach identifier is divided into 2, namely: Global Identifier is
an identifier that is declared outside the function and placed above all functions in a program
and local identifier is an identifier that is declined in the function, including in the parameter
list. The reach is limited to the function itself.
o Passing parameters are one function that calls another function to carry out certain tasks, to
the function called (Called Function) is given all the data needed to carry out the tasks given
by the caller's function. Delivery of parameters in language c there are 2 types namely call by
value and call by reference/location
o Recursive (recursion) is a process that calls him back. In the recursive C language carried out
by function.
ThankYOU...
REFERENCES

o Paul Deitel & Harvey Deitel. (2022). C how to program. 09. Pearson Education. Hoboken.
ISBN: 978-0-13-739839-3. Chapter 5
o Functions in C: http://aelinik.free.fr/c/ch15.htm

You might also like