Di Posting Oleh : Simple Learning
Kategori : example Recursion recursive-function-example-code
This c++ tutorial contains
- What is a recursion?
- What are its important parts
- A simple example code
- How it affects stack
A function calls it self until a certain condition is true
A recursive function has two important parts
1. Base case, Stopping state, stopping condition
2. Functions call its self with a specific conditions (Recalling condition)
When a function calls occur in a program it pushes into the stack. So if a function is calling itself again and again (Recursive Calling) it will be pushing again and again on the stack every time it will push new resources will be allocated for a new call.
Base Case:
Its a condition when it becomes true or executes function stop to call it self
Recalling Condition:
A condition in which function recalls it self with a specific parameters or it depends on the required result we want to get.
- Lets write a simple example to understand the how recursive function works.
- In this example an integer 'n' is passing to a function in which its value is incrementing by one in recalling condition.
- When its value becomes 11 or greater than 10 (base case) it returns all calls.
#include<iostream> |
Its output:
Lets have a look to this program it has a problem what
#include<iostream> |
When we run the above code our program get crashes why?
When a function is called it puts on to the stack. In the above program function is calling itself again and again and putting its calls on the stack again and again where stack is reserving some resources for each call.
So the stacks are not in large size and when stack becomes full our program get crashes. This is why because there is not a base case in program where function will stop putting itself on stack.
It is recommended to understand the concept do experiment with the code and analyze the output and also dry run the code on paper. Another example in c++
0 Response to "Recursive function in c++ programming"
Post a Comment