Tech Point Fundamentals

Tuesday, December 28, 2021

C# Program to Swap Two Numbers without Temp Variable

C# Program to Swap Two Numbers without Temp Variable

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


How can you swap two numbers without using any temp variable? Write a program that is free from the IntegerOverflow exception as well.




C# Program To Swap Two Numbers Without Third Variable


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Swapping without Temp Variable

using System;

public class Program
{
 public static void Main()
 {
   int num1 = 10;			
   int num2 = 20;
   Console.WriteLine("Numbers Before Swapping : ");
   Console.WriteLine(String.Format("Number-1 : {0}, Number-2 : {1}", num1, num2));	
   Console.WriteLine("\n");
   Console.WriteLine("Numbers After Swapping using Sum Logic : ");
   Swapping(num1, num2);
   Console.WriteLine("\n");
   Console.WriteLine("Numbers After Swapping using XOR Logic : ");
   SwappingByXOR(num1, num2);
 }	  	
	
public static void Swapping(int num1, int num2)    
{	          
  num1 = num1 + num2;
  num2 = num1 - num2;
  num1 = num1 - num2;
  
  Console.WriteLine(String.Format("Number-1 : {0}, Number-2 : {1}", num1, num2));			
}	
	
public static void SwappingByXOR(int num1, int num2)    
{	          
  num1 = num1 ^ num2;
  num2 = num1 ^ num2;
  num1 = num1 ^ num2;
  
  Console.WriteLine(String.Format("Number-1 : {0}, Number-2 : {1}", num1, num2));	
}	
}





Output: 


Numbers Before Swapping : 
Number-1 : 10, Number-2 : 20


Numbers After Swapping using Sum Logic : 
Number-1 : 20, Number-2 : 10


Numbers After Swapping using XOR Logic : 
Number-1 : 20, Number-2 : 10



Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.