Index « Previous Next »

Question

Write a program that prompts the user to enter number in two variables and Swap the contents of the variables. (Do not declare extra variable.)

Source Code

#include <stdio.h>

int main()
{
    int num1, num2;

    printf("Enter first number :");
    scanf("%d", &num1);
    printf("Enter second number :");
    scanf("%d", &num2);

    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    printf("After swapping, first is %d and second is %d.", num1, num2);

    return 0;
}

Output

Enter first number :10
Enter second number :16
After swapping, first is 16 and second is 10.