C Program to Swap Two Numbers

Last Updated:

C Program to Swap Two Numbers

In programming, there are two different techniques to swap any two numbers in a variable, they are

  • Swap using Temporary Variable
  • Swap without using Temporary Variable

Swap using Temporary Variable

In the following example, we will swap two numbers (25 and 50) using a temporary variable (temp).

Example

C Compiler
#include <stdio.h> int main() { int num1 = 25; int num2 = 50; int temp = 0; temp = num1; num1 = num2; num2 = temp; printf("After swapping..."); printf("\nnum1 = %d", num1); printf("\nnum2 = %d", num2); return 0; }

Swap without using Temporary Variable

In the following example, we will swap two numbers (25 and 50) without using a temporary variable.

Example

C Compiler
#include <stdio.h> int main() { int num1 = 25; int num2 = 50; num1 = num1 - num2; num2 = num1 + num2; num1 = num2 - num1; printf("After swapping..."); printf("\nnum1 = %d", num1); printf("\nnum2 = %d", num2); return 0; }

Swap any Two Given Numbers

In the following example, we will swap any two given numbers without using a temporary variable (temp).

Example

C Compiler
#include <stdio.h> int main() { int num1, num2; printf("Enter a (int) Number1: "); scanf("%d", &num1); printf("Enter a (int) Number2: "); scanf("%d", &num2); num1 = num1 - num2; num2 = num1 + num2; num1 = num2 - num1; printf("\nAfter swapping..."); printf("\nnum1 = %d", num1); printf("\nnum2 = %d", num2); return 0; }

Share this Page

Meet the Author