GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

C Program to swap two numbers using bitwise XOR

We start the programs, by reading the input. The input to the program is two numbers. Let the two numbers be ‘a’ and ‘b’ of type integer. 

Input: ‘a’ and ‘b’ (int)

Output: Swapped values of ‘a’ and ‘b’

Reading input,

scanf("%d%d",&a,&b);

Let a = 5 and b = 7

swap two numbers

Bit pattern of a and b

Please refer to this on how to get the bit pattern.

swap two numbers

We perform the XOR of a and b (a ^ b) and we get the answer as 2. This answer we store either in a or b.

Note: XOR forms an abelian group under set of integers.

swap two numbers

If we store the answer of a^b in a, that is,

a = a ^ b;
swap two numbers

If we perform a^b again, we get 5. We want to store the 5 in b, therefore we write,

swap two numbers
b = a ^ b;
swap two numbers

To get 7 back, we write a^b

swap two numbers
a = a ^ b;
sort two numbers

C Program

#include<stdio.h>
int main()
{
int a, b;
printf("Enter two numbers:");
scanf("%d%d",&a,&b);

a = a ^ b;
b = a ^ b;
a = a ^ b;

printf("a=%d\nb=%d\n",a,b);
return 0;
}

Note: This logic can only be applied on integers as bitwise operators are only applicable on integers.

Output window

swap two numbers
Scroll to Top