C# programs to swap two numbers without using third variable have been shown here. The algorithm, pseudocode and time complexity of the programs have been covered here. Check here the flowchart of the programs.
Page content(s):
1. Program & Output: Using addition and subtraction
2. Program & Output: Using division and multiplication
Additional content(s):
1. Algorithm (using addition, subtraction)
2. Algorithm (using multiplication, division)
3. Pseudocode (using addition, subtraction)
1. C# Program & output to Swap Two Numbers Without Third Variable (Using Addition and Subtraction)
Code has been copied
/* ******************************************* alphabetacoder.com C# program to swap two numbers without third variable but using arithmetic operators + and - ******************************************* */ using System; namespace Swap { class Program { static void Main(string[] args) { //declare and initialize variable int num1 = 5, num2 = 10; //show numbers before swapping Console.WriteLine("Before swapping: number1 = " + num1 + " and number2 = " + num2); //do swapping using + and - num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; //show numbers after swapping Console.WriteLine("After swapping: number1 = " + num1 + " and number2 = " + num2); // wait for user to press any key Console.ReadKey(); } } }
Output
Before swapping: number1 = 5 and number2 = 10
After swapping: number1 = 10 and number2 = 5
2. C# Program & output to Swap Two Numbers Without Third Variable (Using Multiplication and Division)
Code has been copied
/* ******************************************* alphabetacoder.com C# program to swap two numbers without third variable but using arithmetic operators * and / ******************************************* */ using System; namespace Swap { class Program { static void Main(string[] args) { //declare and initialize character variable int num1 = 5, num2 = 10; //show numbers before swapping Console.WriteLine("Before swapping: number1 = " + num1 + " and number2 = " + num2); //do swapping using * and / num1 = num1 * num2; num2 = num1 / num2; num1 = num1 / num2; //show numbers after swapping Console.WriteLine("After swapping: number1 = " + num1 + " and number2 = " + num2); // wait for user to press any key Console.ReadKey(); } } }
Output
Before swapping: number1 = 5 and number2 = 10
After swapping: number1 = 10 and number2 = 5