C Program to swap two numbers using pointers


In this program, You will learn how to swap two numbers using pointers in c.


Before swap: 15 10

After swap: 10 15

Example: How to swap two numbers using pointers in c.

#include<stdio.h>

int main() {

   int x, y, temp;
   int *a, *b;

   a = &x;
   b = &y;

   printf("Enter two numbers:");
   scanf("%d%d", &x, &y);

   temp = *a;
   *a = *b;
   *b = temp;

   printf("After swap x is:%d", x);
   printf("\nAfter swap y is:%d", y);

   return 0;
}

Output:

Enter two numbers:10 20                                                                                                                
After swap x is:20                                                                                                                     
After swap y is:10