C program to swap two numbers using four different methods

In this C program, we are going to learn how to swap two integer numbers using different methods; here we are going to use four different methods?

Given two integer numbers and we have to swap them using different methods in C language.

The methods that we are going to use in this program are:

1. Using third variable
2. Without using third variable
3. Using X-OR operator
4. Using simple statement
﻿

```//C program to swap two numbers using four different methods.

#include <stdio.h>

int main()
{
int a,b,t;
printf(" Enter value of A ?  ");
scanf("%d",&a);
printf(" Enter value of B ?  ");
scanf("%d",&b);

printf("\n Before swapping : A= %d, B= %d",a,b);

/****first method using third variable*/
t=a;
a=b;
b=t;
printf("\n After swapping (First method) : A= %d, B= %d\n",a,b);

/****second method without using third variable*/
a=a+b;
b=a-b;
a=a-b;
printf("\n After swapping (second method): A= %d, B= %d\n",a,b);

/****Third method  using X-Or */
a^=b;
b^=a;
a^=b;
printf("\n After swapping (third method) : A= %d, B= %d\n",a,b);

/****fourth method  (single statement)*/
a=a+b-(b=a);
printf("\n After swapping (fourth method): A= %d, B= %d\n",a,b);

return 0;
}
```

Output

```Enter value of A ?  100
Enter value of B ?  200

Before swapping : A= 100, B= 200
After swapping (First method) : A= 200, B= 100

After swapping (second method): A= 100, B= 200

After swapping (third method) : A= 200, B= 100

After swapping (fourth method): A= 100, B= 200
```

TOP Interview Coding Problems/Challenges

Learn PCB Designing: PCB DESIGNING TUTORIAL

 Recommended posts C Tips & Tricks, C++ Tips & Tricks Introduction to Linux (Its modes, Safety, Most popular Applications) Linux Best Distros of 2018 C programming optimization techniques Differences b/w C & Embedded C? Embedded C Interview Q. & A. C programming tips for Embedded Development Basic rules of writing a C program Important points (rules) to remember while writing C/C++ program Top 5 Websites for solving programming challenges Read more...

 Others... Computer G.K. (MCQ) Most viewed pages... Categories...

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates