swap() function in C++


The swap() function is used to swap two numbers. By using this function, you do not need any third variable to swap two numbers.

Here is the syntax of swap() in C++ language,

void swap(int variable_name1, int variable_name2);

If we assign the values to variables or pass user-defined values, it will swap the values of variables but the value of variables will remain same at the actual place.

Here is an example of swap() in C++ language,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   int x = 35, y = 75;
   printf("Value of x :%d",x);
   printf("\nValue of y :%d",y);
   swap(x, y);
   printf("\nAfter swapping, the values are: x = %d, y = %d", x, y);
   return 0;
}

Output

Value of x :35
Value of y :75
After swapping, the values are: x = 75, y = 35

It is better that we pass the values to the variables by reference, it will swap the values of variables at actual place.

Here is another example of swap() in C++ language,

Example

 Live Demo

#include <stdio.h>
void SwapValue(int &a, int &b) {
   int t = a;
   a = b;
   b = t;
}
int main() {
   int a, b;
   printf("Enter value of a : ");
   scanf("%d", &a);
   printf("\nEnter value of b : ");
   scanf("%d", &b);
   SwapValue(a, b);
   printf("\nAfter swapping, the values are: a = %d, b = %d", a, b);
   return 0;
}

Output

Enter value of a : 8
Enter value of b : 28
After swapping, the values are: a = 28, b = 8

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements