How to swap two numbers in C?

#include <stdio.h>

int main(void) {
    int a = 10, b = 20, t;

    t = a;  a = b;  b = t;           // with a third variable
    printf("%d %d\n", a, b);

    a = a + b;  b = a - b;  a = a - b;   // without a third variable
    printf("%d %d\n", a, b);
    return 0;
}

Output:

Output of the above program is

20 10
10 20

In a function, send the addresses (swap(&a, &b)) and use pointers. See Call by Value and Reference.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.