C Program to Swap Two Numbers

Swapping two numbers in C programming means swapping the values of two variables. For example, there are two variables m & n. Value of m is “2” & value of n is “3”.
Before Swapping: m value = 2; n value = 3
After Swapping: m value = 3; n value = 2

Problem Description

Write a C program that swaps the values of two variables based on user input.

Problem Solution

1. Prompt the user to input two integers.
2. Pass their addresses to a function, here we call it swap and we don’t need to return anything from it as by swapping the addresses, the values in the variables also get changed.
3. Use an another temporary variable to help in swapping.
4. In the main function, print the values to show that yes, the values have definitely changed and then exit.

Let’s discuss different ways to swap two numbers in C language.

Method 1: Swap Two Numbers using Naive Approach

In this method, we will use another temporary variable to help in the swapping of the two numbers.

Program/Source Code

Here is the source code of the C program that will swap the values inside two variables using temporary variable. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

advertisement
advertisement
  1. /*
  2. * C program to read two integers M and N and to swap their values.
  3. * Use a user-defined function for swapping by accepting the addresses of the two variables.
  4. * Output the values of M and N before and after swapping.
  5. */
  6.  
  7. #include <stdio.h>
  8.  
  9. /*  Function swap - to interchanges the contents of two items */
  10.  
  11. void swap(float *ptr1, float *ptr2)
  12. {
  13.     // Step 4. Create a temporary variable for storing the values
  14.     float temp;
  15.     temp = *ptr1;
  16.     *ptr1 = *ptr2;
  17.     *ptr2 = temp;
  18. }
  19.  
  20. int main(void)
  21. {
  22.     float m, n;
  23.     // Step 1. Take user input
  24.     printf("Enter the value of M (accepted decimal values): ");
  25.     scanf("%f", &m);
  26.     printf("Enter the value of N (accepted decimal values): ");
  27.     scanf("%f", &n);
  28.     // Step 2. Show the values before passing their addresses to the function
  29.     printf("Before swapping : M = %5.2f\tN = %5.2f\n", m, n);
  30.     // Step 3. Pass the addresses to the function
  31.     swap(&m, &n);
  32.     // Step 5. Print the values after the swap function has executed
  33.     printf("After swapping : M  = %5.2f\tN = %5.2f\n", m, n);
  34. }
Program Explanation

1. Take the two integers as input and store it in the variables m and n respectively.
2. Show the values before passing their addresses to the function.
3. Call function swap. Pass addresses of variables to the function swap.
4. Receive the addresses by the two pointers ptr1 and ptr2.
5. Create a temporary variable for storing the values.
6. First copy the address &m to the variable temp.
7. Copy the address at &n to &m.
8. Copy the address temp (which was &m previously) to &n.
9. Print the variables m and n as output after the swap function has executed and exit.

Example:
Given two numbers, M=13 and N=12.
1. We will assign M value to temp variable i.e. temp = 13.
2. After that we will assign N to M => N = M i.e. M = 12.
3. Assign temp to N : N = temp i.e N = 13.

Time Complexity: O(1)
As there is no array or loops involved, the order remains 1 even then the code becomes more precise and uses less variables throughout the approaches.

Note: Join free Sanfoundry classes at Telegram or Youtube

Space Complexity: O(1)
Since we use constant space, the complexity of space is O(1).

Run Time Testcases

Testcase 1: Here, we are entering the integers 13 and 12 as input.

 
Enter the value of M (accepted decimal values): 13
Enter the value of N (accepted decimal values): 12
Before swapping : M = 13.00    N = 12.00
After swapping : M  = 12.00    N = 13.00

Testcase 2: Here, we are entering decimal values as input.

Enter the value of M (accepted decimal values): 4324.14311
Enter the value of N (accepted decimal values): 32331.5342
Before swapping : M = 4324.14    N = 32331.54
After swapping : M  = 32331.54    N = 4324.14

advertisement
Method 2: Swap Two Numbers without using any Temporary Variable

In this approach, we will swap two integers without using any temporary variables and bitwise operations.

Program/Source Code

Here is source code of the C program that will swap two numbers without using any temporary variables and bitwise operations. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Swap two Integers without using Temporary Variables
  3.  * and Bitwise Operations
  4.  */
  5. #include <stdio.h>
  6.  
  7. // function to swap the two numbers
  8. void swap(float *ptr1, float *ptr2)
  9. {
  10.     // Step 4. As ptr1 gets the sum of both, in the next step obviously ptr2 
  11.     // gets the difference of the sum and ptr2 which is ptr1
  12.     *ptr1 = *ptr1 + *ptr2;
  13.     *ptr2 = *ptr1 - *ptr2;
  14.     *ptr1 = *ptr1 - *ptr2;
  15. }
  16.  
  17. int main(void)
  18. {
  19.     float m, n;
  20.     // Step 1. Take user input
  21.     printf("Enter the value of M (accepted decimal values): ");
  22.     scanf("%f", &m);
  23.     printf("Enter the value of N (accepted decimal values): ");
  24.     scanf("%f", &n);
  25.     // Step 2. Show the values before passing their addresses to the function
  26.     printf("Before swapping : \t M = %5.2f\tN = %5.2f\n", m, n);
  27.     // Step 3. Pass the addresses to the function
  28.     swap(&m, &n);
  29.     // Step 5. Print the values after the swap function has executed
  30.     printf("After swapping : \t M  = %5.2f\tN = %5.2f\n", m, n);
  31. }
Program Explanation

1. Take the two integers as input and store it in the variables m and n respectively.
2. Show the values before passing their addresses to the function.
3. Call function swap. Pass addresses of variables to the function swap.
4. Receive the addresses by the two pointers ptr1 and ptr2.
5. Add ptr1 and ptr2 and store their result in ptr1.
6. Take the difference of ptr1 (ptr1 + ptr2) and ptr2, the difference is obviously ptr1, store it in ptr2.
7. Remeber that ptr1 is still the sum of original ptr1 and ptr2 so the difference between ptr1 and ptr2 will be ptr2 which gets stored in ptr1.
8. Print the variables m and n as output after the swap function has executed and exit.

advertisement

Time Complexity: O(1)
As there is no array or loops involved, the order remains 1 even then the code becomes more precise and uses less variables throughout the approaches.

Space Complexity: O(1)
Since we use constant space, the complexity of space is O(1).

Run Time Testcases

Testcase 1: Here, we are entering 436.687 and 76.98 as input.

Enter the value of M (accepted decimal values): 436.687
Enter the value of N (accepted decimal values): 76.98
Before swapping :     M = 436.69    N = 76.98
After swapping :     M  = 76.98    N = 436.69

Testcase 2: Here, we are entering 34.4523 and 213.0004 as input.

Enter the value of M (accepted decimal values): 34.4523
Enter the value of N (accepted decimal values): 213.0004
Before swapping :     M = 34.45    N = 213.00
After swapping :     M  = 213.00    N = 34.45

Method 3: Swap Two Numbers using Bitwise XOR

Swap two integers without using any temporary variable and using the XOR operator.

An XOR operator basically for a number of inputs, gives one/true only if the number of one’s in the input is odd.

Program/Source Code

Here is a source code of the C program that will swap two numbers without using any temporary variables and using the XOR operator. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2. * C program to read two integers M and N and to swap their values.
  3. * Use a user-defined function for swapping by accepting the addresses of the two variables.
  4. * Output the values of M and N before and after swapping.
  5. */
  6.  
  7. #include <stdio.h>
  8.  
  9. /*  Function swap - to interchanges the contents of two items */
  10.  
  11. void swap(long *ptr1, long *ptr2)
  12. {
  13.     // Step 4. Performing XOR operation on the values
  14.     *ptr1 = *ptr1 ^ *ptr2;
  15.     *ptr2 = *ptr1 ^ *ptr2;
  16.     *ptr1 = *ptr1 ^ *ptr2;
  17. }
  18.  
  19. int main(void)
  20. {
  21.     long m, n;
  22.     // Step 1. Take user input
  23.     printf("Enter the value of M (accepted decimal values): ");
  24.     scanf("%ld", &m);
  25.     printf("Enter the value of N (accepted decimal values): ");
  26.     scanf("%ld", &n);
  27.     // Step 2. Show the values before passing their addresses to the function
  28.     printf("Before swapping : M = %5ld\tN = %5ld\n", m, n);
  29.     // Step 3. Pass the addresses to the function
  30.     swap(&m, &n);
  31.     // Step 5. Print the values after the swap function has executed
  32.     printf("After swapping : M  = %5ld\tN = %5ld\n", m, n);
  33. }
Program Explanation

1. Take the two integers as input and store it in the variables m and n respectively.
2. Show the values before passing their addresses to the function.
3. Call function swap. Pass addresses of variables to the function swap.
4. Receive the addresses by the two pointers ptr1 and ptr2.
5. Perform XOR operations.
6. Print the variables m and n as output after the swap function has executed and exit.

XOR Operations
Let’s understand this using a simple example:

  • Suppose the user enters m as 12 and n as 15.
  • The values are then passed on to the void swap(long, long) function.
  • Here, we need to take the binary representation of the numbers in account.
  • So, 12 is 1100 and 15 is 1111.
  • XOR on 12 and 15 gives 0011 = 3, stored in ptr1
  • XOR on 3 and 15 gives 1100 = 12, stored in ptr2
  • XOR on 3 and 12 gives 1111 = 15, stored in ptr1
  • Thus the values get swapped by XOR, a nifty little tool for solving many problems really efficiently.

Time Complexity: O(1)
As there is no array or loops involved, the order remains 1 even then the code becomes more precise and uses less variables throughout the approaches.

Space Complexity: O(1)
Since we use constant space, the complexity of space is O(1).

Run Time Testcases
Enter the value of M (accepted decimal values): 4234145445
Enter the value of N (accepted decimal values): 3241234534
Before swapping : M = 4234145445    N = 3241234534
After swapping : M  = 3241234534    N = 4234145445

Method 4: Swap Two Numbers without using Temporary Variables or Arithmetic Operator

In this approach, we take input from the user and swaps the contents of two numbers using bitwise XOR operation and without using any temporary variables or arithmetic operator.

Program/Source Code

Here is source code of the C program to swap the contents of two numbers using bitwise XOR operation. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C program to swap the contents of two numbers using bitwise XOR operation.
 * Don't use either the temporary variable or arithmetic operators.
 */
#include <stdio.h>
 
void main()
{
    long i, k;
 
    printf("Enter two integers \n");
    scanf("%ld %ld", &i, &k);
    printf("\n Before swapping i= %ld and k = %ld", i, k);
    i = i ^ k;
    k = i ^ k;
    i = i ^ k;
    printf("\n After swapping i= %ld and k = %ld", i, k);
}
Program Explanation

In this C program, we are reading two integers using ‘i’ and ’k’ integer variables respectively. To swap the integer values without using a temporary variable or arithmetic operators. The bitwise XOR operator is used to copy the bit if it is set in one operand but not both. Print the swapped values of numbers.

Runtime Test Cases
 
Enter two integers
45
89
 
Before swapping i= 45 and k = 89
After swapping i= 89 and k = 45

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.