# Ruby program to swap two numbers using the Bitwise XOR (^) operator

Ruby Example: Write a program to swap two numbers using the Bitwise XOR (^) operator.
Submitted by Nidhi, on December 03, 2021

Problem Solution:

In this program, we will create two integer variables with some initial values. Then we will interchange the values of variables and print the interchanged values.

Program/Source Code:

The source code to swap two numbers using the bitwise XOR (^) operator is given below. The given program is compiled and executed successfully.

```# Ruby program to swap two numbers
# using the Bitwise XOR (^) operator

num1=5
num2=3

print "Number before swapping:\n"
print "num1: ",num1,"\n"
print "num2: ",num2,"\n"

num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2

print "\nNumber after swapping:\n"
print "num1: ",num1,"\n"
print "num2: ",num2,"\n"
```

Output:

```Number before swapping:
num1: 5
num2: 3

Number after swapping:
num1: 3
num2: 5
```

Explanation:

In the above program, we created two integer variables num1, num2 that are initialized with 5, 3 respectively. Then we interchanged the values of variables using the XOR (^) operator and printed the result using the print() function.

Preparation

What's New

Top Interview Coding Problems/Challenges!