0% found this document useful (0 votes)
2 views23 pages

02 Recursive

The document provides an overview of recursive functions in programming, explaining their definition, components, and how they work. It includes examples of recursion, such as calculating factorials and Fibonacci sequences, and emphasizes the importance of base cases in recursive algorithms. Additionally, it outlines the differences between direct and indirect recursion and offers practice exercises for implementing recursive functions in C++.

Uploaded by

monycc2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

02 Recursive

The document provides an overview of recursive functions in programming, explaining their definition, components, and how they work. It includes examples of recursion, such as calculating factorials and Fibonacci sequences, and emphasizes the importance of base cases in recursive algorithms. Additionally, it outlines the differences between direct and indirect recursion and offers practice exercises for implementing recursive functions in C++.

Uploaded by

monycc2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Data structure &

Programming II
Topic: Recursive function

1
Outline

▪ Review on Function

▪ What is recursive function?

▪ How to use recursive

▪ Examples and Practices

2
Review on Function

3
Function
❑ What and Why?
▪ A function is a block of code that performs a specific task. A function may
return a value.

▪ Why function?
✓ A large and complex program can be divided into smaller programs
✓ assign task and work in team is easy

✓ Program is easy to understand, fix error, and maintain


✓ Reusable code
✓ A function can be call again and again anytime and anywhere in the program

4
Function
❑ Type of function

▪ There are two types of functions in C programming (likewise, in C++):


1. Standard library functions
Library Provided functions
▪ Also called: built-in function, or existing function stdio.h printf(), scanf()
▪ For example, see Table 1 math.h pow(), sqrt(), ceil(),
floor(), cos(), sin()
2. User-defined functions
▪ Also called: user-custom function

▪ For example, a user (programmer) defines his/her own function to do something

5
Syntax C language
❑ Create Function with returning value
c) Parameter of a function
It has parameter type and parameter name
If have more than one, separate them by comma
type functionName(type parameter1){
... .. ... b) Name of function
... .. ... it should start with a verb

return value;
} int sumTwoNumber(int n1, int n2){
int s;
s=n1+n2;
a) Type of value returning d) Return value return s;
from the function It must be the same data type as a) }

Ex1: Create a function to do


summation of two numbers 6
Syntax C language
❑ Create Function with no returning value
c) Parameter of a function
It has parameter type and parameter name
If have more than one, separate them by comma
void functionName(type parameter1){
... .. ... b) Name of function
... .. ... it should start with a verb

return value;
}
void greetMessage(char name[20]){
printf(“Hi, %s”, name);
printf(“Welcome back!”);
a) Void means no returning d) No need to return value since we
value from the function use void in a) }

Ex1: Create a function to display a


greet message for a person 7
Example of functions
❑ Returning Vs. Non-returning value function
▪ Function with returning value ▪ Function with no returning value

int sum(int a, int b){


void display(int a){
int res=0;
printf(“Hello %d\n”, a);
printf(“This function has no
res=(a+b)*2;
returning value”);
n++;
printf(“use the keyword void”);
return res;
}
}

8
Syntax C language
❑ How to execute the created function?
▪ The execution of a C program begins from the main( ) function.
▪ Our user-defined function can be executed by calling it from main() function

#include <stdio.h> #include <stdio.h>


void functionName(){ int functionName1(){
... .. ... ... .. ...
return 5;
... .. ... }
} void functionName2(){
... .. ...
... .. ...
int main(){ }
... .. ...
... .. ... int main(){
int result;
... .. ...
functionName();
result=functionName1();
functionName2();
... .. ... ... .. ...
... .. ... ... .. ...
} }
9
Function
❑ Global Vs. Local variable
#include <stdio.h>
Global variables
▪ Local variable a variable that creates inside a int n=0;
function char name[10];
int sum(int a, int b){
✓ Its value can not be accessed from outside int res=0;

Function
User-defined

Local variables
the function
res=(a+b)*2;
✓ Its value will be destroyed after the function n++;
finish executing return res;
Output: }

int main(){
int num=10;
▪ Global value is variable that creates int res=2;

outside the function below all library inclusion printf("*Start program \n");
✓ Its value can be accessed from any functions printf(“%d”, sum(2,5));
res = sum(2,5)
✓ Its value will be destroyed after the whole printf(“%d”, res);
program finish executing printf(“%d”, n);
Call created function
} 10
Recursive Function

11
Recursive
❑ Definition

▪ A recursion is an algorithm which calls itself with smaller (or simpler) input values

▪ In programming languages, recursion is the ability given to a function to call itself

▪ To write a recursive program, the following steps are needed


1. Find a recursive decomposition of the problem (find cases which allow to call itself again)
▪ Express solution in general case

2. Find the stop condition (find base case)


▪ Check that the stop condition is reached after a finite number of recursive calls in all cases

12
Recursive
❑ Definition
▪ Recursive function is a function that calls itself repetitively until certain condition is satisfied.
It works like a loop

▪ Component of recursive function


▪ A condition to determine when the function should call itself again (keep repetition)
[repeat case or general case]
▪ A condition to determine when the function should not call itself again (stopping condition) [base case]

Remark: When call itself again, we should update its parameter in order to reach the stopping condition
▪ If-else statement
▪ A return statement
13
Recursive
❑ Example of recursion in factorial

▪ The factorial of a positive integer n, denoted by


▪ n! = 1*2*…*(n-1)*n = (n-1)! *n

▪ To calculate n!, we just know how to calculate (n-1)! then multiple by n

▪ The subproblem (n-1)! is the same as the initial problem, BUT a simpler case
since n-1 < n

14
How to do it in coding?

15
Recursive
❑ Example of recursion in calculating a factorial number

▪ Calculate factorial Function fac(n: integer): integer


Begin function
▪ n! = 1 if n<=1 if(n<=1) then
return 1
▪ n! = ((n-1)!) * n if n>1
else
return (fac(n-1))*n
end if
End function

An example of a recursive function to


calculate a factorial number

16
Example of recursion in
Suit Fibonacci
0 1 1 2 3 5 8 13 21 34

17
Recursive
❑ Example of recursion in Suit Fibonacci

▪ Suit Fibonacci Function fibo(n: integer): integer


Begin function
▪ Un=1 if n<=2 if(n==1 OR n==2) then
return 1
▪ Un=Un-1+Un-2 if n>=3
else
return fibo(n-1)+fibo(n-2)
end if
End function

An example of a recursive function in


pseudo code to calculate the nth element
of suit fibonacci

18
Recursive
❑ Example of recursion Summation

▪ Sum Function sum(n: integer): integer


Begin function
▪ F(n) = n + f(n-1) when n>1 if(??) then
return ??
▪ F(n)=1 when n=1
else
return ??
end if
End function

An example of a recursive function in


pseudo code to computer summation
Using recursive to find summation
S=1+2+3+…+n
19
Recursive
❑ Remark

▪ Base case is a case that it does not call to the main problem. It stops recursive

▪ In each call of recursive, it should tend to reach the base case.

20
Recursive: Direct and Indirect
❑ Definition

▪ Direct recursive
▪ Subproblem uses the main problem to call for defining the result

▪ Indirect recursive
▪ Subproblem A calls subproblem B

▪ Example
f(x)=1 if x=1
f(x)=1 if x=1 or x=2 f(x)=g(x)+2 if x>1
f(x)=f(x-1)*f(x-2) if x>2 g(x)=0 if x=2
g(x)=f(x)-1 if x>2
Direct recursive Indirect recursive 21
Practice
Write a C++ program using recursive to ….

1. Calculate the summation (2 + 4 + 6 +… + n)/n using recursive where n is a


number input by a user

2. Display the message Hello 1, Hello 2, …, Hello n, where n is an input given


from user.

3. Count the number of digits in an integer input by a user using recursive


function.

22
Q&A

23

You might also like