You are here: Home / Topics / C# program to swap two numbers without using temporary variable

C# program to swap two numbers without using temporary variable

Filed under: C# on 2023-09-21 06:58:23

Here you will find an algorithm and program in C# programming language to swap 2 numbers without using any third or temporary variable.

Swapping two number : Swap two numbers means exchange the values of two variables with each other. Suppose we are given 2 numbers num1 = 10 and num2 = 20 and we have to swap these 2 numbers without using third variable. After swaping value of num1 = 20 and num2 = 10.
 

Algorithm to swap two numbers without using third variable
 

START
Step 1 ->  Take two integer as input num1 and num2.
Step 2 ->  Print number before swapping
Step 3 ->  num1 = num1 + num2;
Step 4 ->  num2 = num1 - num2;
Step 5 ->  num1 = num1 - num2;
Step 6 ->  Print numbers after swapping
STOP


C# Program to Swap Two Numbers Without Using Temporary Variable
 

using System;
class LFC {
static void Main() {
 int num1=10,num2=15;
 Console.WriteLine("Number before swapping is "+num1+" and "+num2);
 num1=num1+num2;
 num2=num1-num2;
 num1=num1-num2;
 Console.WriteLine("Number After swapping is "+num1+" and "+num2);
}
}

Output
Enter Two Numbers :
10 15
Number before swapping is 10 and 15
Number after swapping is 15 and 10


About Author:
G
Geetam     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.