w3resource

JavaScript: Check whether a given integer is within 20 of 100 or 400

JavaScript Basic: Exercise-19 with Solution

Write a JavaScript program to check whether a given integer is within 20 of 100 or 400.

Sample Solution:

JavaScript Code:

// Define a function named testhundred that takes a parameter x
function testhundred(x) {
  // Return true if the absolute difference between 100 and x is less than or equal to 20,
  // or the absolute difference between 400 and x is less than or equal to 20; otherwise, return false
  return ((Math.abs(100 - x) <= 20) || (Math.abs(400 - x) <= 20));
}

// Log the result of calling the testhundred function with the argument 10 to the console
console.log(testhundred(10));

// Log the result of calling the testhundred function with the argument 90 to the console
console.log(testhundred(90));

// Log the result of calling the testhundred function with the argument 99 to the console
console.log(testhundred(99));

// Log the result of calling the testhundred function with the argument 199 to the console
console.log(testhundred(199));

// Log the result of calling the testhundred function with the argument 200 to the console
console.log(testhundred(200));

Output:

false
true
true
false
false

Live Demo:

See the Pen JavaScript: Number in a range- basic-ex-19 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Check a given integer is within 20 of 100 or 400

ES6 Version:

 // Using ES6 arrow function syntax to define the testhundred function
const testhundred = (x) => ((Math.abs(100 - x) <= 20) || (Math.abs(400 - x) <= 20));

// Log the result of calling the testhundred function with the argument 10 to the console
console.log(testhundred(10));

// Log the result of calling the testhundred function with the argument 90 to the console
console.log(testhundred(90));

// Log the result of calling the testhundred function with the argument 99 to the console
console.log(testhundred(99));

// Log the result of calling the testhundred function with the argument 199 to the console
console.log(testhundred(199));

// Log the result of calling the testhundred function with the argument 200 to the console
console.log(testhundred(200));

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to check two given numbers and return true if one of the number is 50 or if their sum is 50.
Next: JavaScript program to check from two given integers, if one is positive and one is negative.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.