Swap two numbers without using third variable in C
In this post, you will learn different ways for swapping two numbers using C programming language. Such a type of question is generally asked in programming interviews, the interviewer may ask to write a program for swapping of two numbers using a particular way.
C Swap two numbers without using temporary variable
In the given C program, we ask the user to enter two integer values and store them in two variables. Then, we swap the entered value using the addition and subtraction operators.
#include<stdio.h>
int main()
{
int x, y;
printf("Enter the value of x and y: ");
scanf("%d %d",&x,&y);
printf("Before swapping: %d %d\n",x,y);
/*Swapping in steps */
x = x + y;
y = x - y;
x = x - y;
/*Verifying swapped values */
printf("After swapping: %d %d",x,y);
return 0;
}
Output of the above code:
Enter the value of x and y: 200 150
Before swapping: 200 150
After swapping: 150 200
C Swap two numbers using Multiplication and division
In the given C program, we swap two numbers using the arithmetic operators multiplication and division.
// C program to swap two variables
#include <stdio.h>
int main()
{
int x, y;
printf("Enter the value of x and y: ");
scanf("%d %d",&x,&y);
printf("Before swapping: %d %d\n",x,y);
// swapping 'x' and 'y' using
// multiplication and division
x = x * y;
y = x / y;
x = x / y;
// Verifying swapped values
printf("After swapping: %d %d",x,y);
return 0;
}
Output of the above code:
Enter the value of x and y: 200 150
Before swapping: 200 150
After swapping: 150 200
C program to swap two numbers using Bitwise XOR
Here, we have used the bitwise XOR operator to swap two variables. The XOR of two numbers x and y returns a number that has all the bits as 1 wherever bits of x and y differ. For example, XOR of 10 (binary 1010) and 5 (binary 0101) is 1111.
#include <stdio.h>
int main()
{
int x = 40, y = 55;
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;
}
Output of the above code:
Before swapping: x = 40, y = 55
After Swapping: x = 55, y = 40
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative