Swapping of two numbers in C

Swapping of two numbers in C
Swapping of two numbers in C

Program for: “Swapping of two numbers in C”

Problem Statement: Given two numbers a and b swap the two numbers such that the value of a becomes b and the value of b becomes a.

Examples:

Example 1:
Input: a = 5 , b = 3
Output: b = 3, a = 5
Explanation: Swapped two numbers

Example 2:
Input: a = 6 , b = 7
Output: b = 7, a = 6
Explanation: Swapped two numbers

Solution:

DisclaimerDon’t jump directly to the solution, try it out yourself first.

Approach:

  • we are given two variables a and b and we need to swap the values of these variables.
  • We take a temporary variable temp.
  • we store the value of a in temp.
  • Then store the value of b in a.
  • Then store the value of temp in b and we have the numbers swapped.

C Program

#include <stdio.h>

int main() {
   int a = 5, b = 3, temp;
   printf("Before swapping a=%d and b=%d\n",a,b);
   
   // swapping values
   temp = a;
   a = b;
   b = temp;

   printf("After swapping a=%d and b=%d",a,b);
}

Output:

Before swapping a=5 and b=3

After swapping a=3 and b=5

Time Complexity: O(1)

You can also convert the above program to create a custom swap function which will swap the values passed in as parameters. Below is the code for the same.

C Program

#include <stdio.h>

int swap(int *a,int *b) {
   int temp = *a;
   *a = *b;
   *b = temp;
   }
int main() {
   int a = 5, b = 3;
   printf("Before swapping a=%d and b=%d\n",a,b);
   swap(&a,&b);
   printf("After swapping a=%d and b=%d",a,b);
}

Output:

Before swapping a=5 and b=3

After swapping a=3 and b=5

Time Complexity: O(1)

Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article