C Program to Swap Two Numbers without using Temporary Variables or Arithmetic Operator

This is a C Program to swap the contents of two numbers using bitwise xor operation.

Problem Description

This C Program swaps the contents of two numbers using bitwise XOR operation.

Problem Solution

Take input from the user and swaps the contents of two numbers using bitwise XOR operation.

Program/Source Code

Here is source code of the C program to swap the contents of two numbers using bitwise XOR operation. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C program to swap the contents of two numbers using bitwise XOR
 * operation. Don't use either the temporary variable or arithmetic
 * operators
 */
#include <stdio.h>
 
void main()
{
    long i, k;
 
    printf("Enter two integers \n");
    scanf("%ld %ld", &i, &k);
    printf("\n Before swapping i= %ld and k = %ld", i, k);
    i = i ^ k;
    k = i ^ k;
    i = i ^ k;
    printf("\n After swapping i= %ld and k = %ld", i, k);
}
Program Explanation

In this C program, we are reading two integers using ‘i’ and ’k’ integer variables respectively. To swap the integer values without using a temporary variable or arithmetic operators. The bitwise XOR operator is used to copy the bit if it is set in one operand but not both. Print the swapped values of numbers.

advertisement
advertisement
Runtime Test Cases
 
$ cc pgm48.c
$ a.out
Enter two integers
45
89
 
Before swapping i= 45 and k = 89
After swapping i= 89 and k = 45

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.