Skip to main content

Swap two numbers in C using different methods

 1. Swap two numbers in C.

#include<stdio.h>

int main()
{
    int a, b;
    scanf("%d%d", &a, &b);

    int temp;
    temp = *x;
    *x = *y;
    *y = temp;

    printf("%d %d", a, b);

    return 0;
}

Monetize your website traffic with yX Media

2. Swap two numbers in C using recursion method.

#include<stdio.h>

void swap(int *x, int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
int main()
{
    int a, b;
    scanf("%d%d", &a, &b);

    swap(&a, &b);

    printf("%d %d", a, b);

    return 0;
}

3. Swap two numbers in C without using any other variable.

#include<stdio.h>

int main()
{
    int a, b;
    scanf("%d%d", &a, &b);

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

    printf("%d and %d", a, b);

    return 0;
}

Comments