Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 7: Swap Two Numbers Without Third Variable

Lesson 8 of 14 in the free C# Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

Aim

To exchange the values of two integer variables without any temporary storage using arithmetic identities, and to evaluate the trade-offs against the XOR swap and the modern tuple swap.

Theory

The sum/difference trick is pure algebra executed on two's-complement integers. After x = x + y, x transiently holds the combined total; y = x - y recovers the ORIGINAL x into y; x = x - y (total minus original x) deposits the original y into x. All three statements are in-place mutations of stack-resident value types. An advanced student must volunteer three caveats. (1) Overflow: x + y can exceed int.MaxValue; in C#'s default unchecked context it wraps modulo 2³² — and remarkably the subsequent subtractions un-wrap the wrap, so the swap still lands correctly, but inside a checked { } block the same code throws OverflowException. (2) The XOR variant (x ^= y; y ^= x; x ^= y;) sidesteps overflow entirely but destroys both values when x and y alias the SAME storage location (x ^ x = 0) — a genuine hazard with ref parameters. (3) The idiomatic modern C# swap is tuple deconstruction (x, y) = (y, x);, which the compiler lowers to hidden temporaries and which can never surprise you. The "no third variable" exercise is therefore a probe of two's-complement understanding, not a production technique — modern register allocators make the temp variable free anyway.

Requirements

  • .NET SDK 8.0+ or the RUN CODE button; commands: dotnet new console, dotnet run.

Procedure

  1. Create the project: dotnet new console -n SwapLab, cd SwapLab, paste Program.cs.
  2. Run dotnet run and confirm the values crossed over.
  3. Set x = int.MaxValue and wrap the three statements in checked { } to witness OverflowException; then replace the block with (x, y) = (y, x); for contrast.

Explanation of the Code

  • int x = 10, y = 25; — two independent slots in the stack frame; printing "Before Swap" first gives the experiment its control reading.
  • x = x + y; → x becomes 35 — the only moment when information from both variables coexists in one slot.
  • y = x - y; → y = 35 - 25 = 10 — the original x teleports into y.
  • x = x - y; → x = 35 - 10 = 25 — the original y lands in x. Net effect: a 2-cycle permutation achieved with zero auxiliary storage.
  • The final interpolated Console.WriteLine($"After Swap: x = {x}, y = {y}") verifies the postcondition x = 25, y = 10.

Expected Output

Before Swap: x = 10, y = 25
After Swap:  x = 25, y = 10

🎯 Viva Questions

  1. Why does the trick still work if x + y overflows? — Two's-complement addition and subtraction are modular (mod 2³²); the subtraction cancels the wrap in an unchecked context.
  2. When would the same code throw? — Inside checked { } or when compiled with the checked-arithmetic option.
  3. What is the failure mode of the XOR swap? — If both names alias the same variable, the first XOR zeroes it permanently.
  4. What is the idiomatic C# swap today? — Tuple deconstruction: (x, y) = (y, x);.
  5. Does the arithmetic swap work for double? — It executes, but floating-point rounding can corrupt the values — never use it for non-integers.
  6. Where do x and y physically live? — In the method's stack frame, or purely in CPU registers after JIT register allocation.