Coders Packet

Swapping of Numbers Using two variables and Three variables Using Java

By Praveen Kumar. S

In this project, Let's discuss swapping numbers using two variables and three variables in Java. To understand this project, you want to know about data types and how to use them.

It is one of the important logic to be understood at the beginner level in any Programming Language. Swapping of numbers can be done in three ways. At the Beginner level, you have to know to swap numbers at least in two ways. So, let me teach you to swap the numbers in the very easiest ways.

First, Let me teach you to swap the numbers using Three variables.

In this project, you have to create three variables. For example, let the variables be a,b, temp in integer data type. Here, we are going to use the easiest logic to swap the numbers. First, assign the values to a and b. Let the temp variable be empty. 

Then, assign the value of a to temp, the value of b to a, Then the value of temp to b.

Mathematically, 
temp = a;
a = b;
b = temp;

Let's write a program using this concept,

import java.util.Scanner;
public class swappingOfNumbers
{
public static void main(String[] args)
{
int a,b,temp;
System.out.println("ENter The Value of A: ");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
System.out.println("Enter the value of B : ");
b = sc.nextInt();
temp = a;
a = b;
b = temp;
System.out.println("Enter the value of A : "+a);
System.out.println("Enter The Value of B : "+b);
}
}


Output : 

Enter the value of A :
5
Enter the value of B :
10
Enter the value of A: 10
Enter the value of B: 5

 

Then, Let me teach you to swap numbers using Two variables.
In this method, you have to create two variables. For Example, a,b in integer datatype.

Then, assign the values to a and b.
Now, let me explain to you the logic behind this method. assign a to the addition of a and b. assign b to the subtraction of a and b. Then, assign a to the subtraction of a and b.

Mathematically,
a = a+b;
b = a-b;
a = a-b;

Let's write a program using this logic.

import java.util.Scanner;
public class swappingOfNumbers
{
public static void main(String[] args)
{
int a,b;
System.out.println("Enter The Value of A : ");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
System.out.println("Enter The Value of B : ");
b = sc.nextInt();
a = a+b;
b = a-b;
a = a-b;
System.out.println("Enter The Value of A : "+a);
System.out.println("Enter The Value of B : "+b);
}
}

Output : 

Enter the value of A :
5
Enter the value of B :
10
Enter the value of A: 10
Enter the value of B: 5

These are the two easiest ways of swapping of numbers.

 

 

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Praveen Kumar. S (PraveenKumarS)

Download packets of source code on Coders Packet