31 March 2012

Shell Script to swap two numbers without using third variable

2 comments

Q. How do I swap two numbers using addition and subtraction in Bash


Ans:

#!/bin/bash
echo "enter first number"
read a
echo "enter second number"
read b
echo "a before swapping is $a and b is $b"
#swapping
a=$((a+b))
b=$((a - b))
a=$((a-b))
echo "a after swapping is  $a and b is $b"

Output


swapping two numbers using addition and subtraction

Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

2 comments:

  1. Even simpler and without third variable

    #!/bin/bash
    echo "enter first number"
    read a
    echo "enter second number"
    read b
    echo "a before swapping is $a and b is $b"
    #swapping
    read a b <<<"$b $a"
    echo "a after swapping is $a and b is $b"

    ReplyDelete