w3resource

JavaScript: Compute the sum of the two given integers

JavaScript Basic: Exercise-16 with Solution

Sum Two Integers (Triple if Equal)

Write a JavaScript program to compute the sum of the two given integers. If the two values are the same, then return triple their sum.

This JavaScript program calculates the sum of two given integers. If the two integers are the same, it returns triple their sum. It demonstrates conditional statements to determine whether the integers are equal and to perform the appropriate computation accordingly.

Visual Presentation:

JavaScript: Compute the sum of the two given integers

Sample Solution:

JavaScript Code:

// Define a function named sumTriple that takes two parameters, x and y
function sumTriple(x, y) {
  // Check if x is equal to y
  if (x == y) {
    // If true, return three times the sum of x and y
    return 3 * (x + y);
  } else {
    // If false, return the sum of x and y
    return (x + y);
  }
}

// Log the result of calling the sumTriple function with the arguments 10 and 20 to the console
console.log(sumTriple(10, 20));

// Log the result of calling the sumTriple function with the arguments 10 and 10 to the console
console.log(sumTriple(10, 10)); 

Output:

30
60

Live Demo:


Flowchart:

Flowchart: JavaScript - Compute the sum of the two given integers

ES6 Version:

// Using ES6 arrow function syntax to define the sumTriple function
const sumTriple = (x, y) => {
  // Check if x is equal to y
  if (x == y) {
    // If true, return three times the sum of x and y
    return 3 * (x + y);
  } else {
    // If false, return the sum of x and y
    return (x + y);
  }
};

// Log the result of calling the sumTriple function with the arguments 10 and 20 to the console
console.log(sumTriple(10, 20));

// Log the result of calling the sumTriple function with the arguments 10 and 10 to the console
console.log(sumTriple(10, 10));

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that sums two integers and returns triple their sum if the integers are equal.
  • Write a JavaScript program that sums two numbers and returns triple the sum if both numbers are prime and identical.
  • Write a JavaScript program that calculates the sum of two numbers; if they are equal, return thrice the sum, otherwise add a fixed bonus to the sum.

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to get the difference between a given number
Next: JavaScript program to compute the absolute difference between a specified number and 19.

What is the difficulty level of this exercise?

Based on 136 votes, average difficulty level of this exercise is Hard .

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.