Q:

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

belongs to collection: Ruby Basic Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 num1num2 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to set the specific bit using the bit... >>
<< Ruby program to demonstrate the bitwise XOR (^) op...