Last Updated: 27 Jan, 2021

Swap Two Numbers

Easy
Asked in companies
CIS - Cyber InfrastructureErnst & Young (EY)Cybage Software

Problem statement

You are given two numbers 'a' and 'b' as input.


You must swap the values of 'a' and 'b'.


For Example:
Input: 
'a' = 8, 'b' = 5

Output:
5 8

Explanation:
Initially, the value of 'a' and 'b' is 8 and 5, respectively.

After swapping, the value of 'a' is 5, and the value of 'b' is 8.
Input Format:
The first and only input line contains two integers, 'a' and 'b', representing the two numbers. 
Output Format:
The first line of output prints the swapped value of 'a' and 'b'.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.

Approaches

01 Approach

Take input in two integer datatype variables, a and b. Create a temporary variable temp and initialize it equal to a. Now make a equal to b, and finally make b equal to temp. Print a and b.

02 Approach

We can swap values of two variables by using a third variable and instead of that, we can use the arithmetic operation to do it without an extra variable.
The idea is to store the sum of two variables in the first variable. Now if we assign the sum(which is 1st variable) - 2nd variable in the 2nd variable then the value in the 2nd variable will be equal to the 1st variable.
Again assign the first variable equal to the sum(first variable) - 2nd variable(which has a value equal to 1st variable) so 1st variable will now have a value equal to 2nd variable.