Swap Two Numbers (With Temporary Variable)¶
Learning Objectives¶
By the end of this tutorial, you will be able to: - Understand the concept of using a temporary variable for swapping values - Implement swapping algorithms in Java, Python, C, and Oracle PL/SQL - Analyze the time and space complexity of the swapping process - Apply swapping techniques to real-world programming scenarios - Debug common issues that occur during variable swapping
Concept Explanation¶
What is it?¶
Swapping two numbers or values means exchanging their content. For example, if variable A holds 10 and variable B holds 20, after swapping, A will hold 20 and B will hold 10. One common method to achieve this is by using a third, temporary variable to hold one of the values during the exchange process.
Why is it important?¶
Swapping values is a fundamental operation in computer programming. It's used in many algorithms such as sorting (e.g., bubble sort), array manipulations, and various data structure operations where the order or position of elements needs to be changed.
Where is it used?¶
- Sorting Algorithms: Many algorithms, like bubble sort or selection sort, rely on repeatedly swapping elements.
- Array/List Reversal: Reversing the order of elements in a data structure.
- Data Encryption: Certain cryptographic algorithms might involve swapping bits or bytes.
- Game Development: Swapping positions of game objects or character attributes.
Real-world example¶
Imagine two people, Alice and Bob, each holding a different book. If they want to exchange books, they might need a third person (like a librarian) to temporarily hold one book while the exchange happens. Alice gives her book to the librarian, Bob gives his book to Alice, and then the librarian gives Alice's original book to Bob.
Algorithm¶
- Start.
- Get two numbers,
num1andnum2, from the user. - Declare a temporary variable,
temp. - Store the value of
num1intotemp(temp = num1). - Assign the value of
num2tonum1(num1 = num2). - Assign the value of
temptonum2(num2 = temp). - Display the swapped values of
num1andnum2. - End.
Edge Cases: - Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation). - Swapping identical numbers will result in no change, which is correct behavior.
Implementations¶
import java.util.Scanner;
public class SwapNumbersWithTemp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number (num1): ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number (num2): ");
int num2 = scanner.nextInt();
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
// Swapping logic using a temporary variable
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
scanner.close();
}
}
# Get two numbers from the user
num1_str = input("Enter the first number (num1): ")
num1 = float(num1_str)
num2_str = input("Enter the second number (num2): ")
num2 = float(num2_str)
print(f"Before swapping:")
print(f"num1 = {num1}")
print(f"num2 = {num2}")
# Swapping logic using a temporary variable
temp = num1
num1 = num2
num2 = temp
print(f"After swapping:")
print(f"num1 = {num1}")
print(f"num2 = {num2}")
#include <stdio.h>
int main() {
int num1, num2;
int temp; // Temporary variable for swapping
printf("Enter the first number (num1): ");
scanf("%d", &num1);
printf("Enter the second number (num2): ");
scanf("%d", &num2);
printf("Before swapping:\n");
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
// Swapping logic
temp = num1;
num1 = num2;
num2 = temp;
printf("After swapping:\n");
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
return 0;
}
SET SERVEROUTPUT ON;
DECLARE
num1 NUMBER := &Enter_First_Number;
num2 NUMBER := &Enter_Second_Number;
temp_var NUMBER; -- Temporary variable for swapping
BEGIN
DBMS_OUTPUT.PUT_LINE('Before swapping:');
DBMS_OUTPUT.PUT_LINE('Num1: ' || num1);
DBMS_OUTPUT.PUT_LINE('Num2: ' || num2);
-- Swapping logic
temp_var := num1;
num1 := num2;
num2 := temp_var;
DBMS_OUTPUT.PUT_LINE('After swapping:');
DBMS_OUTPUT.PUT_LINE('Num1: ' || num1);
DBMS_OUTPUT.PUT_LINE('Num2: ' || num2);
END;
/
Explanation¶
- Java: Uses a
tempinteger variable to facilitate the swap.Scanneris used for input. - Python: Similarly uses a
tempvariable. Note that Python offers a more concise way to swap (num1, num2 = num2, num1), but this implementation uses a temporary variable for conceptual clarity. - C: Requires a
tempinteger variable.scanf()is used to read input, andprintf()to display. - Oracle: Implemented in PL/SQL. A
NUMBERvariabletemp_varis declared to hold the value temporarily. Substitution variables are used for interactive input.
Complexity Analysis¶
- Time Complexity: O(1) - The number of operations is constant, regardless of the values being swapped.
- Space Complexity: O(1) - Only a single additional temporary variable is used.
Flowchart¶
graph TD
A[Start] --> B[Get num1]
B --> C[Get num2]
C --> D[Declare temp]
D --> E[temp = num1]
E --> F[num1 = num2]
F --> G[num2 = temp]
G --> H[Display num1, num2]
H --> I[End]
Sample Dry Run¶
| Step | num1 | num2 | temp | Description |
|---|---|---|---|---|
| Initial | 5 | 10 | - | Variables initialized |
temp = num1 |
5 | 10 | 5 | num1's value saved in temp |
num1 = num2 |
10 | 10 | 5 | num1 gets num2's value |
num2 = temp |
10 | 5 | 5 | num2 gets original num1's value |
| Final | 10 | 5 | 5 | Values are swapped |
Practice Problems¶
Easy¶
- Modify the program to swap three numbers (e.g., A to B, B to C, C to A).
- Swap two characters instead of numbers.
Medium¶
- Implement swapping without using a temporary variable (using arithmetic or bitwise operations).
- Swap elements in an array at specified indices.
Hard¶
- Implement a generic swap function/method that works with different data types (where applicable by language).
Interactive Elements¶
Try It Yourself¶
Quick Test¶
- What will be the output if we swap the values 15 and 25 using a temporary variable?
- Modify the program to swap three numbers in sequence (A→B, B→C, C→A)
- Create a function that swaps two variables and returns the swapped values
Code Challenge¶
Write a program that: - Takes two numbers as input - Swaps them using a temporary variable - Displays the original and swapped values - Includes error handling for non-numeric input
Learning Path¶
Before This Tutorial¶
- Basic Variables - Understanding variable declaration and assignment
- Input/Output Operations - Reading user input and displaying output
After This Tutorial¶
- Swap Without Temporary Variable - Learn optimization techniques
- Array Element Swap - Apply swapping to data structures
- Sorting Algorithms - Advanced applications of swapping
Related Skills¶
- Memory Management - Understanding memory usage
- Algorithm Analysis - Analyzing code efficiency
- Debugging Strategies - Troubleshooting techniques
Interview Tips¶
- Explain the Logic: Clearly describe why a temporary variable is needed for swapping
- Mention Complexity: State that it's O(1) time and O(1) space complexity
- Discuss Edge Cases: Talk about swapping identical numbers or zero values
- Real-world Applications: Mention sorting algorithms and data structures
- Alternative Methods: Briefly mention that there are ways to swap without temporary variables
Best Practices & Common Mistakes¶
General Programming Principles¶
- Code Organization: General Best Practices
- Debugging: Universal Debugging Strategies
- Performance: Algorithm Analysis Guide
Language-Specific Guidance¶
- Java: Java Best Practices & Common Pitfalls
- Python: Python Best Practices & Common Pitfalls
- C: C Best Practices & Common Pitfalls
- Oracle: Oracle Best Practices & Common Pitfalls
Concept-Specific Considerations¶
- For Swapping Operations: See Performance Implications
- Memory Management: Memory Usage Patterns
Related Concepts¶
- Variables and Assignment: Understanding how values are stored and transferred
- Memory Management: How temporary variables use memory
- Control Structures: Sequential execution of statements
- Data Types: Working with different numeric types
- Algorithm Design: Basic building blocks of larger algorithms
- Sorting Algorithms: Where swapping is frequently used
"Programming is not about typing, it's about thinking." - Rich Hickey
📚 Related Programs¶
- Swap Without Temporary Variable - Learn arithmetic and bitwise swapping techniques
- Swap Three Numbers - Advanced swapping with multiple variables
- Array Element Swap - Swapping elements in arrays