Sure, here is a C# code that swaps two integers without using a third variable:
C#
using System;
public class SwapExample
{
public static void Main(string[] args)
{
int x = 10;
int y = 20;
// Swap x and y without using a third variable.
x = x + y;
y = x - y;
x = x - y;
Console.WriteLine("x = {0}, y = {1}", x, y);
}
}
This code works by adding x and y together, then storing the result in x. Then, it subtracts y from the result, and stores the result in y. Finally, it subtracts x from the result, and stores the result in x. This effectively swaps the values of x and y without using a third variable.
Here is an explanation of how the code works:
The using System; statement imports the System namespace, which contains the Console class.
The public class SwapExample statement defines a class called SwapExample.
The public static void Main(string[] args) statement defines a method called Main that is the entry point for the program.
The int x = 10; statement declares an integer variable called x and initializes it to 10.
The int y = 20; statement declares an integer variable called y and initializes it to 20.
The x = x + y; statement adds y to x and stores the result in x.
The y = x - y; statement subtracts y from x and stores the result in y.
The x = x - y; statement subtracts x from y and stores the result in x.
The Console.WriteLine("x = {0}, y = {1}", x, y); statement prints the values of x and y to the console.
There is a simple C# program to swap to an integer without using a thirdvariable.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Program.SwapInteger();
Console.ReadLine();
}
public static void SwapInteger()
{
int a = 10;
int b = 5;
Console.WriteLine('a = {0}, b = {1}', a, b);
a = a + b; // Now a = 15
b = a - b; // Now b = 15-5=10
a = a - b; // Now a = 15-10=5
Console.WriteLine('a = {0}, b = {1}', a, b);
}
}
}
Output: a = 10, b = 5
a = 5, b = 10
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a C# code that swaps two integers without using a third variable:
C#
This code works by adding x and y together, then storing the result in x. Then, it subtracts y from the result, and stores the result in y. Finally, it subtracts x from the result, and stores the result in x. This effectively swaps the values of x and y without using a third variable.
Here is an explanation of how the code works:
There is a simple C# program to swap to an integer without using a third variable.