Swap Two Numbers in C

To swap two numbers in C programming, there are two ways. The foremost one is to use a third variable. And the second is to use Addition and Subtraction Operators without using a third variable.

In this tutorial, we will write C Programs, where we take two numbers in two integer variables, and swap them using the above said ways.

Method 1 – Use Third Variable

In the following program, we take two values in integer variables a and b, and swap the values in these variables using a temporary third variable temp.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int a = 1, b = 3, temp;
    
    printf("Before swapping\n");
    printf("a : %d\n", a);
    printf("b : %d\n", b);
    
    temp = a;
    a = b;
    b = temp;
    
    printf("After swapping\n");
    printf("a : %d\n", a);
    printf("b : %d\n", b);
    
    return 0;
}

Output

Before swapping
a : 1
b : 3
After swapping
a : 3
b : 1
Program ended with exit code: 0

Method 2 – Without a Temporary Variable

In the following program, we take two values in integer variables a and b, and swap the values in these variables without using a temporary third variable.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int a = 1, b = 3, temp;
    
    printf("Before swapping\n");
    printf("a : %d\n", a);
    printf("b : %d\n", b);
    
    a = b + a;
    b = a - b;
    a = a - b;
    
    printf("After swapping\n");
    printf("a : %d\n", a);
    printf("b : %d\n", b);
    
    return 0;
}

Output

Before swapping
a : 1
b : 3
After swapping
a : 3
b : 1
Program ended with exit code: 0

Conclusion

In this C Tutorial, we learned how to swap two numbers in different ways, with examples.