w3resource

JavaScript: Check from two given integers whether one of them is 8 or their sum or difference is 8

JavaScript Basic: Exercise-40 with Solution

Write a JavaScript program to check from two given integers whether one of them is 8 or their sum or difference is 8.

Pictorial Presentation:

JavaScript: Check from two given integers whether one of them is 8 or their sum or difference is 8

Sample Solution:

JavaScript Code:

// Define a function named check8 with parameters x and y
function check8(x, y) {
  // Check if x or y is equal to 8
  if (x == 8 || y == 8) {
    // Return true if the condition is true
    return true;
  }

  // Check if the sum of x and y is equal to 8 or the absolute difference between x and y is equal to 8
  if (x + y == 8 || Math.abs(x - y) == 8) {
    // Return true if the condition is true
    return true;
  }

  // Return false if none of the conditions are met
  return false;
}

// Log the result of calling check8 with the arguments 7 and 8 to the console
console.log(check8(7, 8));

// Log the result of calling check8 with the arguments 16 and 8 to the console
console.log(check8(16, 8));

// Log the result of calling check8 with the arguments 24 and 32 to the console
console.log(check8(24, 32));

// Log the result of calling check8 with the arguments 17 and 18 to the console
console.log(check8(17, 18)); 

Sample Output:

true
true
true
false

Live Demo:

See the Pen JavaScript: Check from two given integers - basic-ex-40 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Check from two given integers whether one of them is 8 or their sum or difference is 8

ES6 Version:

// Define a function named check8 using arrow function syntax with parameters x and y
const check8 = (x, y) => {
  // Check if x or y is equal to 8
  if (x == 8 || y == 8) {
    return true;
  }

  // Check if the sum of x and y is equal to 8 or the absolute difference is equal to 8
  if (x + y == 8 || Math.abs(x - y) == 8) {
    return true;
  }

  // Return false if none of the conditions are met
  return false;
};

// Log the result of calling check8 with the arguments 7 and 8 to the console
console.log(check8(7, 8));

// Log the result of calling check8 with the arguments 16 and 8 to the console
console.log(check8(16, 8));

// Log the result of calling check8 with the arguments 24 and 32 to the console
console.log(check8(24, 32));

// Log the result of calling check8 with the arguments 17 and 18 to the console
console.log(check8(17, 18));

Previous: JavaScript program to compute the sum of the two given integers, If the sum is in the range 50..80 return 65 other wise return 80.
Next: JavaScript program to check three given numbers, if the three numbers are same return 30 otherwise return 20 and if two numbers are same return 40.

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.