C Program to swap two numbers without using third variable: To implement swapping of numbers but without using the third variable for this we need to perform some basic mathematical operations.

How to swap two numbers without using a third variable?
For swapping number first we have two numbers and without using the third variable we swap numbers by doing a simple mathematical operation (sum and subtract )

Steps for swapping of two numbers
Let us assume variable a, b
1. Add the first and second numbers and store addition in the first variable.
a = a + b
2. Subtract the first and second numbers and store them in the second variable.
b = a – b
3. Subtract the first and second numbers and store them in the first variable.
a = a – b

Example:
a = 10, b = 20;
a = 10+20 => a= 30
b = 30-20 => b = 10
a = 30-10 => a=20
Result a = 20, b = 10;

C Program to swap two numbers without using third variable

#include<stdio.h>

void main()

{

int first,second ;

printf("Enter first\n");

scanf("%d",&first);

printf("Enter second\n");

scanf("%d",&second);

printf("before swaping\n first =%d \n second =%d\n"first, second);

first = first + second;

second = first - second;

first = first - second;

printf(" after swaping\n first=%d\n second=%d",first,second);

}

 

Output:

C Program to swap two numbers without using third variable

Write A Comment