DEV Community

Shubham Jadhav
Shubham Jadhav

Posted on

ODD-EVEN Number using Recursion in JS πŸš€

Hello Guys, Today is this article we are taking about Recursion.
We are solving and understanding a problem by using Recursion in JavaScript.

πŸ‘‰ Problem :- Find odd-even number using Recursion ?

Let's start today's article...

β€’ What is recursion?
=> Recursion mean calling itself till condition not true. A function call itself that's function called Recursive function.

β€’ How to find odd even number in JavaScript?
=> We are finding odd-even number by dividing 2. When the reminder is 0 it's mean the number is even or reminder is 1, it is odd number. Right...

We are using same logic in today's solving problem using recursion but different.

πŸ‘‰ Let's start solving problems

β€’ First we create a function and pass one parameter. As following πŸ‘‡

img1

β€’ We are using same logic as we use always to find odd even number but in this problem we are consider if the parameter's value is 0 it is even or if it's value is 1 it means number is odd.

β€’ See following code to better understand, we are using if-else condition. πŸ‘‡
img2

β€’ Now time to use recursion function but before using recursion we simply decrease parameter 'num' value by 2.
Because odd and even number difference is 2 for example 1 and 3 difference is 2 and also 2 and 4 difference is 2. See below πŸ‘‡
img3

β€’ In the above code, in a line number 14 we are calling a function that's mean it will call itself till when given condition not true.

β€’ Let's check the output πŸ‘‡
img4

πŸ™ Thanks for reading...
πŸ‘‰ Stay with us for more....

Top comments (3)

Collapse
 
dev_shubham profile image
Shubham Jadhav

Thanks for reading...
I was solving by using recursion above problem. That's why it's long solution.

Collapse
 
pierrewahlberg profile image
Pierre Vahlberg

If you want to make a new article, going down each sub array in an array (branches of a tree) would probably be a more useful scenario as well as more illustrative to the naivity of depth/iterarions 🀟

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

The author could write another post on trampolining to show how to avoid this