ADVERTISEMENT
ADVERTISEMENT

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.

Ruby Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.