Program to Swap Two Numbers

This program is to swap/exchange two numbers by using a variable in C, Java and Python.

#include <stdio.h> int main() { int x, y, t; printf("Enter the value of X:"); scanf("%d", &x); printf("\nEnter the value of Y:"); scanf("%d", &y); printf("\n\nBefore Swapping:"); printf("\nX = %d Y = %d", x, y); t = x; x = y; y = t; printf("\n\nAfter Swapping:"); printf("\nX = %d Y = %d", x, y); }
public class myClass { public static void main(String[] args) { Scanner inp = new Scanner(System.in); int x, y, t; System.out.println("Enter the value of X: "); x = inp.nextInt(); System.out.println("Enter the value of Y: "); y = inp.nextInt(); System.out.println("\nBefore Swapping:"); System.out.println("X = " + x + " Y = " + y); t = x; x = y; y = t; System.out.println("\nAfter swapping:"); System.out.println("X = " + x + " Y = " + y); } }
X = int(input("Enter the value of X:")) Y = int(input("\nEnter the value of Y:")) print("\n\nBefore swapping:") print("X = %d Y = %d" %(X,Y)) temp = X X = Y Y = temp print("\nAfter swapping:") print("X = %d Y = %d" %(X,Y))

We used the temporary variable t, which is assigned the value of the first variable x.

Then, the value of the first variable x is assigned to the second variable y.

Finally, the temporary varibale t (which holds the initial value of x) is assigned to y. This completes the swapping process.