Swap Two Numbers in C

Swapping means exchanging the values stored in two variables. The clearest approach uses a temporary variable because it is easy to read and works without arithmetic-overflow concerns.

Swap Using a Temporary Variable Top ↑

#include <stdio.h>

int main(void) {
    int first = 10;
    int second = 20;

    int temp = first;
    first = second;
    second = temp;

    printf("first = %d, second = %d\n", first, second);
    return 0;
}

Output

first = 20, second = 10

Swap User-Entered Numbers Top ↑

#include <stdio.h>

int main(void) {
    int first;
    int second;

    printf("Enter two integers: ");
    if (scanf("%d %d", &first, &second) != 2) {
        printf("Invalid input.\n");
        return 1;
    }

    int temp = first;
    first = second;
    second = temp;

    printf("After swapping: %d %d\n", first, second);
    return 0;
}

Swap with a Function and Pointers Top ↑

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    int first = 5;
    int second = 8;

    swap(&first, &second);

    printf("%d %d\n", first, second);
    return 0;
}

Learn why pointers let a function modify the caller's variables.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer