swapping 2 numbers without temporary variable code example
Example 1: swapping of two numbers without using third variable in shell script
#!/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"
Example 2: swap 2 numbers without using 3rd variable
a=10;
b=20;
a=a+b;
b=a-b;
a=a-b;
Example 3: swap 2 integers without using temporary variable
using System;
class MainClass {
public static void Main (string[] args) {
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
Console.WriteLine("After swapping: num1 = "+ num1 + ", num2 = " + num2);
Console.ReadLine();
}
}
Example 4: how to swap 2 numbers without 3rd variable
int a = 3;
int b = 5;
a = b*a;
b = a/b
a = a/b