JavaScript: Check whether a number is even or not
JavaScript Function: Exercise-7 with Solution
Write a JavaScript program to check whether a number is even or not.
Visual Presentation:
Sample Solution:
Using recursion:
JavaScript Code:
// Recursive JavaScript function to check if a number is even.
function is_even_recursion(number) {
// If the number is negative, convert it to its absolute value.
if (number < 0) {
number = Math.abs(number);
}
// Base case: If the number is 0, it's even.
if (number === 0) {
return true;
}
// Base case: If the number is 1, it's odd.
if (number === 1) {
return false;
} else {
// Recursive case: Subtract 2 from the number and recursively check the new number.
number = number - 2;
return is_even_recursion(number);
}
}
// Example usage: Check if certain numbers are even.
console.log(is_even_recursion(234)); // true
console.log(is_even_recursion(-45)); // false
console.log(is_even_recursion(65)); // false
Output:
true false false
Flowchart:
Live Demo:
See the Pen javascript-recursion-function-exercise-7 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to get the first n Fibonacci numbers.
Next: Write a JavaScript program for binary search.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-recursion-function-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics