Swap two numbers using pointers

C program to swap two numbers using pointers

Program

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

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

    printf("\n\nBefore swapping");
    printf("\nFirst Number\t:%d",num1);
    printf("\nSecond Number\t:%d",num2);

    ptr1 = &num1;
    ptr2 = &num2;

    temp = *ptr1;
    *ptr1 = *ptr2;
    *ptr2 = temp;

    printf("\n\nAfter swapping");
    printf("\nFirst Number\t:%d",num1);
    printf("\nSecond Number\t:%d",num2);

    getch();

}

Output

Enter the first number  :4
Enter the second number :5


Before swapping
First Number    :4
Second Number   :5

After swapping
First Number    :5
Second Number   :4

Explanation

In the above program, two variables 'num1' and 'num2' are taken, and two pointer variables 'ptr1' and 'ptr2' are also taken, ptr1 points to num1 and ptr2 points to num2 using the statements
ptr1 = &num1;
ptr2 = &num2;
ptr1 contains the address of variable num1 and ptr2 contains address of variable num2.

*ptr1 means "value at the address contained in ptr1". ptr1 contains the address of num1. so, *ptr1 means "value at num1" which is the first number entered by the user i.e. 4
Similarly, *ptr2 = 5

Swapping is done using the following concept
temp = *ptr1; temp = 4
*ptr1 = *ptr2; *ptr1 = 5
*ptr2 = temp; *ptr2 = 4