w3resource

JavaScript: Swap three numbers

JavaScript Math: Exercise-75 with Solution

Write a JavaScript program to swap three numbers without a third variable.

Test Data:
(100, 200, 300) -> 300, 100, 200

Sample Solution:

JavaScript Code:

/**
 * Swaps the values of three variables using arithmetic operations.
 * @param {number} x - The first number.
 * @param {number} y - The second number.
 * @param {number} z - The third number.
 * @returns {Array} - An array containing the swapped values of x, y, and z.
 */
function test(x, y, z)
{
    // Calculate the sum of x, y, and z and assign it to x
    x = x + y + z;
    // Calculate y's new value using arithmetic operations
    y = x - (y + z);
    // Calculate z's new value using arithmetic operations
    z = x - (y + z);
    // Calculate x's new value using arithmetic operations
    x = x - (y + z);
    // Return an array containing the swapped values
    return [x, y, z];  
}
 
// Initialize variables x, y, and z
x = 100; 
y = 200; 
z = 300;

// Display the values before swapping
console.log("Before swapping:")
console.log("x = "+x);
console.log("y = "+y);
console.log("z = "+z);

// Call the test function to swap the values and store the result
result = test(x, y, z);

// Display the values after swapping
console.log("After swapping:");
console.log("x = "+result[0]);
console.log("y = "+result[1]);
console.log("z = "+result[2]);

Output:

Before swapping:
x = 100
y = 200
z = 300
After swapping:
x = 300
y = 100
z = 200

Flowchart:

JavaScript: Swap three numbers

Live Demo:

See the Pen javascript-math-exercise-75 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Hexadecimal number to binary equivalent.
Next: Subtract without arithmetic operators.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-math-exercise-75.php