WAP using a function void swap(int n1, int n2) to swap the numbers stored in n1 and n2 without using a third variable. Print the numbers before and after interchange.
Answers
SOLUTION.
The given code is written in Java.
import java.util.*;
public class SwapNumbers{
void swap(int n1,int n2){
System.out.println("Before Swapping - ");
System.out.println("n1 = "+n1);
System.out.println("n2 = "+n2);
n1+=n2;
n2=n1-n2;
n1-=n2;
System.out.println("After Swapping - ");
System.out.println("n1 = "+n1);
System.out.println("n2 = "+n2);
}
public static void main(String s[]){
Scanner _=new Scanner(System.in);
System.out.print("Enter first number: ");
int a=_.nextInt();
System.out.print("Enter second number: ");
int b=_.nextInt();
(new SwapNumbers()).swap(a,b);
}
}
SAMPLE I/O.
Enter first number: 10
Enter second number: 20
Before Swapping -
n1 = 10
n2 = 20
After Swapping -
n1 = 20
n2 = 10
See attachment for verification.