Q:

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

belongs to collection: C# Basic Programs | basics

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# | print type, max and min value of various data... >>
<< C# | Find the addition of two integer numbers...