Write a program to swap values of two variables using third variable.
Answers
Answer:
I am doing the program in Java. The solution is simple as follows:
import java.util.Scanner;//Using only the scanner class of util package
public class Swapping
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);//creating object(sc) of Scanner class
int a,b,c=0;//Declaring the variables
System.out.println("Enter the first number:");
a=sc.nextInt();//Input of the first number
b=sc.nextInt();//Input of the second number
c=b;//storing the value of variable b in variable c
b=a;//storing the value of variable a in variable b
a=c;//storing the value of variable c in variable a(it actually has the value of variable b)
System.out.println("After swapping the first number becomes:"+a);
system.out.println("After swapping the second number becomes:"+b);
}
}
Try this out. I hope that no problem will occur but if any problem occurs then let me know. Happy to help you :)
Explanation: