Swap 2 numbers using third variable

C program to swap two numbers using third variable.

Program

#include<stdio.h>
#include<conio.h>
void main()
{
    int num1, num2, temp;

    printf("Enter the numbers to be swapped\t:");
    scanf("%d%d", &num1, &num2);

    printf("Before Swapping\n num1 = %d\n num2 = %d\n",num1,num2);

    // logic for swapping
    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("\n\nAfter Swapping\n num1 = %d\n num2 = %d\n",num1,num2);

    getch();
}

Output

Enter the numbers to be swapped :4
5
Before Swapping
 num1 = 4
 num2 = 5


After Swapping
 num1 = 5
 num2 = 4

Explanation

In the above program, we are reading the values of both the numbers in variables named 'num1' and 'num2'. A temporary variable 'temp' is used to swap the values.

for swapping, the value of 'num1' gets stored in 'temp',
then the value of 'num2' is stored in 'num1' and
lastly the value of 'temp' is stored to 'num2'.
This is how the value of 'num1' get changed to the value of 'num2' and vice versa.

Here, temporary variable 'temp' is used to hold the value of first number 'num1' and doesn't have any other use except that.