Swap Two Numbers Without Using 3rd Variable


C Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x,y;
    printf("Enter first Digit:");
    scanf("%d",&x);
    printf("Enter Second Digit:");
    scanf("%d",&y);
    printf("Before swapping x=%d, y=%d",x,y);
    x=x+y;
    y=x-y;
    x=x-y;
    printf("\nAfter  swapping x=%d, y=%d",x,y);
    return 0;
}


Java Program
import java.util.Scanner;

public class Swap {

	public static void main(String[] args) 
	{
		Scanner S = new Scanner(System.in);
		int x,y;
	    System.out.print("Enter first Digit:");
	    x = S.nextInt();
	    System.out.print("Second Digit:");
	    y = S.nextInt();
	    System.out.print("Before swapping x = " + x + " y = " + y);
	    x=x+y;
	    y=x-y;
	    x=x-y;
	    System.out.print("\nAfter  swapping x = " + x + " y = " + y);
	   
	}

}


Python Program
x = int(input("Enter a number: "))
y = int(input("Enter another number:"))
print("Before swapping :")
print("x is " + str(x) + " Y is " + str(y))
x=x+y
y=x-y
x=x-y
print("After swapping :")
print("x is " + str(x) + " Y is " + str(y))

0 Comments:

Post a Comment