🚀Beginner

Swap Two Numbers

Swap values using temp variable

Swapping means exchanging the values of two variables. This is a fundamental operation used in sorting algorithms, data manipulation, and many other programming scenarios.

🔄 Why Learn Swapping?

  • Essential for sorting algorithms (Bubble Sort, Selection Sort)
  • Used in array manipulation
  • Fundamental concept in data structures

Method 1: Using Temporary Variable

swap_temp.c
C
1#include <stdio.h>
2
3int main() {
4 int a = 10, b = 20, temp;
5
6 printf("Before: a = %d, b = %d\n", a, b);
7
8 // Swap using temp variable
9 temp = a; // temp = 10
10 a = b; // a = 20
11 b = temp; // b = 10
12
13 printf("After: a = %d, b = %d\n", a, b);
14 return 0;
15}
Output

Before: a = 10, b = 20

After: a = 20, b = 10

Step-by-Step Execution:

1
temp = a

Store value of a (10) in temp. Now: a=10, b=20, temp=10

2
a = b

Copy value of b to a. Now: a=20, b=20, temp=10

3
b = temp

Copy temp to b. Now: a=20, b=10, temp=10

Method 2: Without Temporary Variable

swap_arithmetic.c
C
1#include <stdio.h>
2
3int main() {
4 int a = 10, b = 20;
5
6 printf("Before: a = %d, b = %d\n", a, b);
7
8 // Swap without temp (arithmetic method)
9 a = a + b; // a = 30
10 b = a - b; // b = 10
11 a = a - b; // a = 20
12
13 printf("After: a = %d, b = %d\n", a, b);
14 return 0;
15}

Note: The arithmetic method can cause overflow with very large numbers. The temp variable method is safer and more readable.

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples