# C# program to swap two numbers with and without using third variable

C# program: Learn how to swap two integer numbers in C#, here we are swapping the numbers by using two methods - using third variable and without using third variable.
Submitted by Ridhima Agarwal, on September 10, 2017

Given two integer numbers and we have to swap them.

We are swapping numbers using two methods:

### 1) Swapping using third variable

To swap numbers, we use a temporary variable to holds the value, firstly we assign first variable to the temporary variable then assign second variable to the first variablecand finally assigns value which is in temporary variable (which holds first number) to the second variable.

Consider the program:

```using System;
namespace swap
{
class ab
{
static void Main(String[] args)
{
int a=5,b=3,temp;

//swapping
temp=a;
a=b;
b=temp;

Console.WriteLine("Values after swapping are:");
Console.WriteLine("a="+a);
Console.WriteLine("b="+b);
}
}
}
```

Output

```Values after swapping are:
a=3
b=5
```

### 2) Swapping without using third variable

Here, we do not use any extra variable to swap the numbers. There are some set of statements (with mathematical operations which performs on the numbers), which swaps the values of variable which are using in these operations.

Example: If we have to swap the values of variable a and b, then the set of statements to swap them, are:

```a=a+b;
b=a-b;
a=a-b;
```

Consider the program:

```using System;
namespace swap
{
class ab
{
static void Main(String[] args)
{
int a=10,b=20;

//swapping
a=a+b;
b=a-b;
a=a-b;

Console.WriteLine("Values after swapping are:");
Console.WriteLine("a="+a);
Console.WriteLine("b="+b);
}
}
}
```

Output

```Values after swapping are:
a=20
b=10
```

ADVERTISEMENT
ADVERTISEMENT

What's New (MCQs)

ADVERTISEMENT

Top Interview Coding Problems/Challenges!

ADVERTISEMENT

ADVERTISEMENT

Comments and Discussions!

IncludeHelp's Blogs

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

© https://www.includehelp.com some rights reserved.