Step by Step C++ Program to Swap Two numbers

0

C++ is a useful programming language that can help us to write program for different purposes. It is one of the most common language that is being taught in schools and colleges. In your college time you must have learnt different programs. Below we have shared a C++ program to swap two numbers.

 

C++ Program to Swap two numbers

“*/

#include <iostream>
using namespace std;

void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}

int main() {
int a = 5, b = 10;
cout << “Before swap: a = ” << a << ” b = ” << b << endl;
swap(a, b);
cout << “After swap: a = ” << a << ” b = ” << b << endl;
return 0;
}

*/”

Also Check: How to Delete all Mails from Single Sender

Let us take some other values

Note: Ignore the double quotes, don’t use them while executing the program

“*/

#include <iostream>
using namespace std;

void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}

int main() {
int a = 10, b = 15;
cout << “Before swap: a = ” << a << ” b = ” << b << endl;
swap(a, b);
cout << “After swap: a = ” << a << ” b = ” << b << endl;
return 0;
}

*/”

 

 

C++ Program to swap two numbers using Pointers.

  1. #include<iostream.h>
  2. #include<conio.h>
  3. void main() {
  4. clrscr();
  5. int *a,*b,*temp;
  6. cout<<“Enter value of a and b:”;
  7. cin>>*a>>*b;
  8. temp=a;
  9. a=b;
  10. b=temp;
  11. cout<<“nAfter swapingna=”<<*a<<“nb=”<<*b;
  12. getch();
  13. }

so, this was the C++ program to swap two numbers. If you have any queries, feel free to ask us in the comments section. Stay tuned to TechAdvises for more such C++ programs and free coding tutorials.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.