swap two numbers using only two variables code example

Example 1: 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 2: how to swap 2 numbers without 3rd variable

int a = 3;
int b = 5;
a = b*a;
b = a/b
a = a/b

Tags:

Java Example