C Program to Swap Two Numbers

Published: 19 Dec 2024
Reading Time: 10 min read

Introduction

Swapping two numbers is a useful operation that can find applications in many different programs like sorting and data manipulation. Although it sounds basic, knowing it is essential. When we talk about the C program to swap two numbers, it means to switch their positions. For example, if two values are attached to variables A and B, swapping makes B take the value of A and A take the value of B.

Example

Input: a = 15, b = 10
Output: a = 10, b = 15

This is one of those programs that can be considered as one of the building blocks that will give you good practice and develop your coding skills. In this article, we'll go through swapping techniques using alternative approaches to help enhance your flexibility with variable manipulation in C programming.

Table of Contents

Approach to Swap Two Numbers in C

There are multiple approaches to swap two numbers in C, and here are the ones that will be discussed in this article:

1. Swapping Two Numbers Using a Third Variable or Temporary Variable

This is the most straightforward and commonly used method to swap two numbers. First, a temporary third variable is introduced to hold the value of one variable while swapping. For example, the value of A is stored in the temporary variable C, then A is assigned the value of B, and finally, B is given the stored value. It's really simple to exchange values this way.

2. Swap Without Third Variable

This approach relies on a set of arithmetic operations, either addition and subtraction or multiplication and division. For example, the sum of A and B is stored in A, and the original values are derived back using simple equations. This method avoids using extra memory.

3. Swapping Function in C

In this method, a function is written to encapsulate the swapping logic, making the code reusable. You will pass two variables as arguments, and the function swaps their values. This approach makes your program much clearer.

4. Swapping Two Numbers Using Pointers in C

Pointers add another layer of flexibility. Here, instead of passing variables directly, their memory addresses are passed to a function which uses these addresses to manipulate the variable values directly.

Method 1: C Program to Swap Two Numbers Using Third Variable

In this approach, we swap two numbers using a third variable (temporary variable).

Code Example

#include <stdio.h>
int main()
{
	int var1, var2, temp;
	printf("Enter two integers \n");
	scanf("%d%d", &var1, &var2);
	printf("Before Swappingn First variable = %d\nSecond variable = %d \n", var1, var2);
	temp = var1;
	var1 = var2;
var2 = temp;
	printf("After Swappingn First variable = %d\nSecond variable = %d\n", var1, var2);
	return 0;
}

Output

Enter two integers
2 3
Before Swapping, First variable = 2
Second variable = 3
After Swapping, First variable = 3
Second variable = 2

Explanation

In the above program, the temp variable is assigned the value of the first variable. Then, the value of the first variable is assigned to the second variable. Finally, the temp (which holds the initial value of the first) is assigned to the second. This completes the swapping process.

Method 2: C Program to Swap Two Numbers Without Using Third Variable

We can swap two numbers without using a third variable. There are three common ways to swap two numbers without using a third variable:

Approach 2.1: By Addition and Subtraction (+ and -)

#include <stdio.h>
int main()
{
	int var1, var2, temp;
	printf("Enter two integers\n");
	scanf("%d%d", &var1, &var2);
	printf("Before Swapping\nFirst variable = %d\nSecond variable = %d\n", var1, var2);
	var1 = var1 + var2;
	var2 = var1 - var2;
	var1 = var1 - var2;
	printf("After Swapping\nFirst variable = %d\nSecond variable = %d\n", var1, var2);
	return 0;
}

Output

Enter two integers
5 6
Before Swapping
First variable = 5
Second variable = 6
After Swapping
First variable = 6
Second variable = 5

Approach 2.2: By Multiplication and Division (* and /)

#include <stdio.h>

int main() {
    int Var1, Var2;

    printf("Enter two integers:\n");
    scanf("%d%d", &Var1, &Var2);

    printf("Before swapping:\nVar1 = %d\nVar2 = %d\n", Var1, Var2);

    // Ensure Var2 is not zero to avoid division by zero
    if (Var2 != 0) {
        // Swap logic
        Var1 = Var1 * Var2;
        Var2 = Var1 / Var2;
        Var1 = Var1 / Var2;

        printf("After swapping:\nVar1 = %d\nVar2 = %d\n", Var1, Var2);
    } else {
        printf("Swapping not possible with zero using this method.\n");
    }

    return 0;
}

Output

Enter two integers:
3 6
Before swapping:
Var1 = 3
Var2 = 6
After swapping:
Var1 = 6
Var2 = 3

Approach 2.3: Using Bitwise XOR Operator

The bitwise XOR operator can also be used to swap two variables.

#include <stdio.h>

int main() {
    int Var1, Var2;

    printf("Enter two integers:\n");
    scanf("%d%d", &Var1, &Var2);

    printf("Before swapping:\nVar1 = %d\nVar2 = %d\n", Var1, Var2);

    // Swap logic using XOR
    Var1 = Var1 ^ Var2;
    Var2 = Var1 ^ Var2;
    Var1 = Var1 ^ Var2;

    printf("After swapping:\nVar1 = %d\nVar2 = %d\n", Var1, Var2);

    return 0;
}

Output

Enter two integers:
2 5
Before swapping:
Var1 = 2
Var2 = 5
After swapping:
Var1 = 5
Var2 = 2

Method 3: C Program to Swap Two Numbers Using Pointers

This approach demonstrates swapping of two numbers in C using pointers.

Code Example

#include <stdio.h>
int main()
{
	int var1, var2, *num1, *num2, temp;
	printf("Enter the value of var1 and var2\n");
	scanf("%d%d", &var1, &var2);
	printf("Before Swapping\nvar1 = %d\nvar2 = %d\n", var1, var2);
	num1 = &var1;
	num2 = &var2;
	temp = *num2;
	*num2   = *num1;
	*num1   = temp;
	printf("After Swapping\nvar1 = %d\nvar2 = %d\n", var1, var2);
	return 0;
}

Output

Enter the value of var1 and var2
1 2
Before Swapping
var1 = 1
var2 = 2
After Swapping
var1 = 2
var2 = 1

Method 4: C Program to Swap Two Numbers Using Functions

This demonstrates the C program to swap two numbers using functions.

Code Example

void swap(int *num1, int *num2)
{
	int temp = *num1;
	*num1 = *num2;
	*num2 = temp;
}
int main()
{
	int var1, var2;
	printf("Enter Value of var1 ");
	scanf("%d", &var1);
	printf("\nEnter Value of var2 ");
	scanf("%d", &var2);
	swap(&var1, &var2);
	printf("\nAfter Swapping: var1 = %d, var2 = %d", var1, var2);
	return 0;
}

Output

Enter the value of var1 and var2
5 7
Before Swapping
var1 = 5
var2 = 7
After Swapping
var1 = 7
var2 = 5

Method 5: C Program to Swap Two Numbers Using One Line Expression

The one-line approach does not need a temporary variable.

Code Example

#include <stdio.h>

int main() {
    int var1, var2;

    printf("Enter two integers:\n");
    scanf("%d%d", &var1, &var2);

    printf("Before swapping:\nVar1 = %d\nVar2 = %d\n", var1, var2);

    // One-line swap using arithmetic operations
    var1 = (var1 + var2) - (var2 = var1);

    printf("After swapping:\nVar1 = %d\nVar2 = %d\n", var1, var2);

    return 0;
}

Output

Enter two integers:
2 8
Before swapping:
Var1 = 2
Var2 = 8
After swapping:
Var1 = 8
Var2 = 2

Conclusion

As you can see, the C program to swap two numbers can be written in different ways. You can derive the same result from a third variable, pointers or arithmetic operations. It's important to practice these codes to build your foundational skills. If you're a student starting out, learning different ways to approach a problem is critical to building a successful career in software programming. To be job-ready, take up a course such as CCBP 4.0 Academy and build all the necessary skills to transition directly into a role as a software professional.

Frequently Asked Questions

1. Can I swap numbers in C without using a third variable?

Yes, you can use arithmetic operations like addition and subtraction or multiplication and division to swap values.

2. Does C have a swap command?

No, there is no standard command to swap variables in C.

3. What concepts are used to swap numbers in C?

Swapping numbers uses variables, pointers, functions, arithmetic operations and temporary variables in C.

4. What are some real-world applications of swapping two numbers in C?

Swapping is used in sorting algorithms, memory optimization tasks, and situations where data needs to be rearranged or exchanged between variables.

5. Which is the best approach to swap variables?

The best approach depends on the problem. Using the third variable is the simplest method. If memory has to be saved, swapping without a third variable and bitwise XOR works. Pointers work well for large data structures.

Related Articles


About NxtWave

NxtWave offers comprehensive programming courses including CCBP 4.0 Academy to help students build job-ready skills in software development.

Contact Information: