Amazon Affiliate

Friday 27 May 2016

Swap two variables in ruby.

#Swapping two variables in ruby :

puts "Enter first variable :"
a = gets.to_i
puts "Enter second variable :"
b = gets.to_i

puts "the value of a is :#{a}"
puts "the value of b is :#{b}"

puts "After exchanging the value :"

# Ist method

a,b = b,a
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"

#2nd method using temporary variable

c = a
a = b
b = c
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"

#3rd method using arithmetic operation

a = a+b
b = a-b
a = a-b
puts "the value of a is :#{a}"
puts "the value of b is :#{b}"