Swap two values
Swap two integer variables by passing them to a method by reference.
Course progress
Problem 54 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
first = 12; second = 35
Expected output
35 12
What is happening?
Save 12 temporarily, place 35 in the first variable, then place the saved 12 in the second variable.
Solution strategy
Build the right mental model
Save the first value temporarily, assign the second value to the first variable, then restore the saved value into the second.
Core concepts
methods · reference parameters
Complexity
Time O(1), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for swap-two-values
using System;
class Program
{
static void Swap(ref int first, ref int second)
{
int temporary = first;
first = second;
second = temporary;
}
static void Main()
{
int first = 12;
int second = 35;
Swap(ref first, ref second);
Console.WriteLine(first + " " + second);
}
}Knowledge check
Questions students often ask
What is the main idea behind swap two values?
Save the first value temporarily, assign the second value to the first variable, then restore the saved value into the second.
What is the time and space complexity of this solution?
Time O(1), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.