Swap Two Numbers in C

Swap Two Numbers in C

Swap Two Numbers in C

Below is a simple C program that swaps two numbers using a temporary variable:

#include <stdio.h>

int main() {
    int a, b, temp;

    // Input the numbers
    printf("Enter the first number: ");
    scanf("%d", &a);
    printf("Enter the second number: ");
    scanf("%d", &b);

    // Display the numbers before swapping
    printf("Before swapping: \n");
    printf("a = %d\n", a);
    printf("b = %d\n", b);

    // Swapping logic using a temporary variable
    temp = a;
    a = b;
    b = temp;

    // Display the numbers after swapping
    printf("After swapping: \n");
    printf("a = %d\n", a);
    printf("b = %d\n", b);

    return 0;
}

Comments

Popular Posts