C-Programming Tutorials

C Program to Swapping Two Numbers Using Bitwise Operators

This C program is used to swapping two numbers, using bitwise operators.

Program:

#include <stdio.h>

int main() {

    int i = 65;

    int k = 120;

    printf(" value of i=%d k=%d before swapping", i, k);

    i = i ^ k;

    k = i ^ k;

    i = i ^ k;

    printf("value of i=%d k=%d after swapping", i, k);

    return 0;

}

Explanation:

i = 65; binary equivalent of 65 is 0100 0001

k = 120; binary equivalent of 120 is 0111 1000

i = i^k;

i...0100 0001

k...0111 1000

---------
val of i = 0011 1001
---------

k = i^k

i...0011 1001

k...0111 1000

---------
val of k = 0100 0001 binary equivalent of this is 65
---------

(that is the initial value of i)

i = i^k

i...0011 1001

k...0100 0001

---------
val of i = 0111 1000 binary equivalent of this is 120
---------

(that is the initial value of k)

 

C Program to Check Whether the Given Number is Even or Odd (Prev Lesson)
(Next Lesson) C Program to Display The Multiplication Table of a Given Number
Back to C-Programming Tutorials
Notice: compact(): Undefined variable: limits in /home/bhimgautam34/public_html/wp-includes/class-wp-comment-query.php on line 853

Notice: compact(): Undefined variable: groupby in /home/bhimgautam34/public_html/wp-includes/class-wp-comment-query.php on line 853

No Comments

Post a Reply

Course Curriculum

error: Content is protected !!