- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
#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
Advertisements