DEV Community

Shubham Jadhav
Shubham Jadhav

Posted on

5 1

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

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools canโ€™t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay