C Program to Swap two Numbers using Bitwise Operators

This C Program Swaps two Numbers using Bitwise operators.

Here is source code of the C Program to Swap two Numbers using Bitwise operators. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Swap two Numbers using Bitwise operators
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. /* Function Prototype */
  8. void swap(int*, int *);
  9.  
  10. void main()
  11. {
  12.     int num1, num2;
  13.     printf("\nEnter two numbers:");
  14.     scanf("%d %d", &num1, &num2);
  15.     printf("\nThe numbers before swapping are Number1= %d Number2 = %d", num1, num2);
  16.     swap(&num1, &num2);        /* Call by Reference to function swap */
  17.     printf("\nThe numbers after swapping are Number1= %d Number2 = %d", num1, num2);
  18. }
  19.  
  20. /* Code to swap two numbers using bitwise operator */
  21. void swap(int *x, int *y)
  22. {
  23.     *x = *x ^ *y;
  24.     *y = *x ^ *y;
  25.     *x = *x ^ *y;
  26. }

$ cc bit27.c
$ a.out
 
Enter two numbers:45 76
The numbers before swapping are Number1= 45 Number2=76
The numbers after swapping are Number1= 76 Number2=45

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

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

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.