0% found this document useful (0 votes)
9 views17 pages

Proyecto

Uploaded by

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

Proyecto

Uploaded by

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

Recursive Functions

For Task.
A recursive function task is a function that calls itself to solve a
smaller instance of the same problem. It consists of a base case and a
recursive case to stop the recursion.
Basic Structure of a Recursive Function

1 Initialization 2 Function Call 3 Termination


Define the base case Function calls itself Base case ends the
and recursive case. with a simpler version recursion.
of the problem.
1 Initialization
Initialization in recursive functions refers to setting the initial state
or value for variables or conditions before the recursive process
begins. This is important because it establishes the starting point
for the recursion and often includes setting the initial parameters
for the first recursive call

2 Function Call
a function call refers to the instance when the function invokes
itself with a new set of parameters. This self-invocation is what
drives the recursion, allowing the function to break down the
problem into smaller, more manageable parts. Here’s a breakdown
of the key components:

Termination
3
Termination in recursive functions refers to the condition that ends
the recursion, preventing it from continuing indefinitely. This is
also known as the base case or base condition. It’s a crucial part of
a recursive function because it defines the point at which the
function should stop calling itself and begin to return values
Base Case and Recursive Case
1 Base Case
The condition that stops the recursive calls.

2 Recursive Case
The part that calls the function within itself.

3 Return Value
What the function returns when the base case is met.
1 Base Case
Every recursive function must have a base case. The base case is the
simplest scenario that does not require further recursion. This is a
termination condition that prevents the function from calling itself
indefinitely. Without a proper base case, a recursive function can
lead to infinite recursion.

2 Recursive Case
In the recursive case, the function calls itself with the modified
arguments. This is the essence of recursion – solving a larger
problem by breaking it down into smaller instances of the same
problem. The recursive case should move closer to the base case
with each iteration.

3 Return Value
This return value is often a simple, known result that can be used to
calculate the results of all the subsequent recursive calls.
Enter
RECURSION TREE
EXAMPLE
 The function starts with the initial call nSum(5), where 5 is the
number you want to sum down to 0.

 The function then calls itself with n - 1,


so nSum(4), nSum(3), nSum(2), nSum(1), and finally nSum(0).

 At nSum(0), the base case is reached, and it returns 0, as there are


no more numbers to add.

 The function then unwinds, adding each number to the sum as it


returns from each recursive call: 1 + nSum(0), 2 + nSum(1), and so
on, until it adds 5 to the result of nSum(4).

 The final sum is the accumulation of all these additions as the


recursion unwinds back to the initial call.
Need of Recursive Function:
A recursive function is a function that solves a problem by solving smaller instances
of the same problem. This technique is often used in programming to solve problems
that can be broken down into simpler, similar subproblems
Examples of Recursive Functions

Fibonacci Tree Traversal Factorial Maze Solving


Sequence Calculation
Navigating through Finding paths
Calculating Fibonacci tree data structures. Computing factorial through a maze.
numbers. of a number.
The Fibonacci sequence is a series of numbers where each number is the sum of
Fibonacci the two preceding ones, usually starting with 0 and 1. In recursive functions for
Sequence tasks, the Fibonacci sequence can be generated by a function that calls itself to
calculate the previous two numbers until it reaches the base case.

Tree traversal in recursive functions refers to the process of visiting each


Tree Traversal node in a tree data structure, exactly once, in a systematic way.

The factorial of a number is the product of all positive integers up to that number. For a
non-negative integer ( n ), the factorial is denoted by ( n! ) and is calculated as:
Factorial n!=n×(n−1)×(n−2)×…×2×1
Calculation For ( n = 0 ), the factorial is defined as ( 1 ).
In recursive functions, the factorial of a number can be calculated by defining a function
that calls itself with a decremented value until it reaches the base case.

Maze solving using recursive functions is a classic computer science


problem that involves finding a path through a maze from a starting
Maze Solving point to an endpoint. The recursive function explores paths by
moving in one direction until it can no longer continue, at which
point it backtracks and tries a different path. This is known as
backtracking.
Fibonacci
Sequence
#include <iostream>
•The fibonacci function is defined to calculate the nth Fibonacci
int fibonacci(int n) { number. It uses a simple recursive algorithm where the base case
if (n <= 1) { returns the input number if it’s 0 or 1. Otherwise, it calls itself to
return n; calculate the two previous Fibonacci numbers and adds them
} else { together.
return fibonacci(n - 1) + fibonacci(n - 2);
} •The main function sets the number of terms (nterms) to 10 and then
}
prints a message indicating the start of the Fibonacci sequence.
int main() { •A for loop runs from 0 to nterms - 1, calling the fibonacci function
int nterms = 10; for each number i and printing the result. This prints the first 10
std::cout << "Fibonacci sequence up to " << numbers in the Fibonacci sequence.
nterms << " terms:" << std::endl;
•The program ends by returning 0, which is a standard way of
for (int i = 0; i < nterms; i++) { indicating that the program has completed successfully.
std::cout << fibonacci(i) << " ";
}

return 0;
}
Tree Traversal

It shows a binary tree with nodes labeled from 1 to 7 and lists the
sequences of nodes visited during inorder, preorder, and postorder
traversals.

• Inorder Traversal: Visits the left subtree, the node, and then the right
subtree. The sequence is 4, 2, 5, 1, 6, 3, 7.

• Preorder Traversal: Visits the node first, then the left subtree, and
finally the right subtree. The sequence is 1, 2, 4, 5, 3, 6, 7.

• Postorder Traversal: Visits the left subtree, the right subtree, and
then the node. The sequence is 4, 5, 2, 6, 7, 3, 1.
#include<iostream> Factorial
using namespace std; Calculation
int factorial(int n);

int main() { • The main() function starts by prompting the user to enter a positive integer
and stores the input in the variable n.
int n; • It then calls the factorial() function, passing n as an argument.
• The factorial() function is defined to call itself recursively. Here’s the
cout << "Enter a positive integer: "; breakdown:
cin >> n; • If n is greater than 1, the function returns n multiplied by the factorial of n -
1. This is the recursive call.
cout << "Factorial of " << n << " = " << • If n is 1 or less, the function returns 1, which is the base case for the
factorial(n); recursion.
The recursion continues until it reaches the base case, where n is 1. At this point,
return 0; the function returns 1, and the recursion starts to unwind, multiplying all the
} numbers from 1 up to the original value of n.

int factorial(int n) {
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
Maze Solving

The function takes a 2D array maze and the current


coordinates (x, y) as arguments. It checks if the current
position is the exit, and if so, returns true. If the
position is not open, it returns false. The function then
recursively tries to move in all four directions (right,
down, left, up) from the current position. If a move
leads to a solution, it returns true; otherwise, it
backtracks by unmarking the current position and
continues to explore other paths. If no path leads to an
exit, the function eventually returns false, indicating
that the maze is unsolvable from the current path.
Advantages of Using Recursive Functions

Clarity Modularity Less Code

Recursive functions Divide complex problems Can often be implemented


represent the problem into simpler, more with less code compared to
explicitly, making the code manageable parts. iterative solutions.
easy to understand.
Common Mistakes in Recursive Functions

1 Missing Base Case 2 Stack Overflow 3 Incorrect State


Update
Forgetting to define a Using excessive
condition to end the memory due to infinite Failing to properly
recursion. recursion. update the state for the
next recursive call.
Tail Recursion and Its Benefits
Definition
A recursive call is the last operation in the calling function.

Optimization
Can be optimized by the compiler to avoid growing the call stack.

Efficiency
Reduces memory consumption and can make recursive functions as
efficient as iterative solutions.
Best Practices for Using Recursive
Functions
Test Extensively Optimize Iteratively
Employ comprehensive testing to Consider iterative approaches if
ensure correctness and prevent recursion leads to performance
infinite recursion. issues.

Document Clearly
Thoroughly document the base case, recursive case, and the expected output.

You might also like