Easy csharp

Swap two numbers without third variable

Problem

Swap values of two integers a = 5 and b = 10 using arithmetic and print the result.

Hints
  • a = a + b; then b = a - b; then a = a - b;

Your practice code

Ready — edit the code above and click Run.

Solution

using System;

class Program
{
    static void Main()
    {
        int a = 5, b = 10;
        a = a + b;
        b = a - b;
        a = a - b;
        Console.WriteLine($"a={a}, b={b}");
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Add/subtract trick: after a=a+b, subtracting b from new a yields original a.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details