Write a C program that swaps the values of two integer varia
Write a C++ program that swaps the values of two integer variables a and b. Use a function swap1(*p1, *p2). Print a and b before and after swapping. Hint: Use a temp variable.
Solution
Two ways to do this Program. I have added both ways.
First way
#include <stdio.h>
 #include<iostream.h>
 void swap1(int *p1,int *p2)
 {
 int tmp;
 tmp = *p1;
 *p1 = *p2;
 *p2 = tmp;
 }
int main()
 {
     int a=5;
     int b=10;
     cout<< \"Before the swap, A is \" << a << \" and B is \" << b << \".\"<< endl;
     swap1(&a,&b);
     cout<< \"After the swap, A is \" << a << \" and B is \" << b << \".\"<< endl;
     return 0;
 }
Second Way
#include <stdio.h>
 #include<conio.h>
 #include<iostream.h>
 void swap1(int &p1,int &p2)
 {
 int tmp;
 tmp = p1;
 p1 = p2;
 p2 = tmp;
 }
int main()
 {
     int a=5;
     int b=10;
     int *p1,*p2;
     p1=&a;
     p2=&b;
     cout<< \"Before the swap, A is \" << a << \" and B is \" << b << \".\"<< endl;
     swap1(*p1,*p2);
     cout<< \"After the swap, A is \" << a << \" and B is \" << b << \".\"<< endl;
     return 0;
 }

