Q:

Write a program swap two numbers without using the third variable?

0

Write a program swap two numbers without using the third variable?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Let’s assume a, b two numbers, there are a lot of methods two swap two numbers without using the third variable.

Method 1( (Using Arithmetic Operators):

#include <stdio.h>
int main()
{
    int a = 10, b = 5;
    // algo to swap 'a' and 'b'
    a = a + b;  // a becomes 15
    b = a - b;  // b becomes 10
    a = a - b;  // fonally a becomes 5
    printf("After Swapping the value of: a = %d, b = %d\n\n", a, b);
    return 0;
}

Method 2 (Using Bitwise XOR Operator):

#include <stdio.h>
int main()
{
    int a = 10, b = 5;
    // algo to swap 'a' and 'b'
    a = a ^ b;  // a becomes (a ^ b)
    b = a ^ b;  // b = (a ^ b ^ b), b becomes a
    a = a ^ b;  // a = (a ^ b ^ a), a becomes b
    printf("After Swapping the value of: a = %d, b = %d\n\n", a, b);
    return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Embedded C interview questions and answers (2022)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What will be the output of the below C program?... >>
<< What will be the output of the below C program?...