C program to swap two numbers

In this program, you will learn about concepts behind c program to swap two numbers with and without using a temporary variable and using the pointer.

C program to swap two integers

For better understanding of program you must have proper knowledge of these c programming topics :

C program to swap two numbers using temporary variable

#include <stdio.h>

int main ()
{
   int num1, num2, temp;

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

   //Swapping process
   temp = num1;
   num1 = num2;
   num2 = temp;

   printf("\nAfter swapping,"
          "\nFirst number: %d"
         "\nSecond number: %d", num1, num2);
 
   return 0;
}

Output
C program to swap two numbers

[adsense1]

C program to swap two numbers without using temporary variable

#include <stdio.h>

int main()
{
   int num1, num2;

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

   //Swapping process
   num1 = num1 + num2;
   num2 = num1 - num2;
   num1 = num1 - num2;

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

   return 0;
}

Output
Output swap number without using temp

C program to swap two numbers using pointer

#include <stdio.h>

int main()
{
   int num1, num2, *x, *y, temp;

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

   //Swapping process
   x = &num1;
   y = &num2;

   temp = *y;
   *y = *x;
   *x = temp;

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

   return 0;
}

Output
Output swap number using pointer