Created
September 11, 2017 19:21
-
-
Save Nitesh-Mishra/8a04c709cfeed73d935faa2516a84b6e to your computer and use it in GitHub Desktop.
Swapping two variables in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Swapping two variables in ruby : | |
| # | |
| # $ ruby swap_two_variables.rb | |
| # Enter first variable : | |
| # 2 | |
| # Enter second variable : | |
| # 3 | |
| # After exchanging the value : | |
| # the value of a is :3 | |
| # the value of b is :2 | |
| # the value of a is :2 | |
| # the value of b is :3 | |
| # the value of a is :3 | |
| # the value of b is :2 | |
| 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 temperory 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}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment