Write a C++ Program to Swap Two Numbers using Pointers.
Object:
Write a program to swap two numbers using pointers. C++ Projects.
Code:
#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
int num1, num2, temp;
int *p1,*p2;
cout<<“Enter Two Numbers.”<<endl;
cout<<“Enter value of a : “;
cin>>num1;
cout<<“Enter value of b : “;
cin>>num2;
p1=&num1;
p2=&num2;
cout<<“\nBefore Swapping two Numbers.\n”;
cout<<“Value of a is : “<<*p1<<endl;
cout<<“Value of b is : “<<*p2<<endl;
//swap
temp = *p1;
*p1 = *p2;
*p2 = temp;
cout<<“\nAfter swapping two Numbers.\n”;
cout<<“Value of a is : “<<*p1<<endl;
cout<<“Value of b is : “<<*p2<<endl;
getch();
}
#include<iostream> #include<conio.h> using namespace std; void main() { int num1, num2, temp; int *p1,*p2; cout<<"Enter Two Numbers."<<endl; cout<<"Enter value of a : "; cin>>num1; cout<<"Enter value of b : "; cin>>num2; p1=&num1; p2=&num2; cout<<"\nBefore Swapping two Numbers.\n"; cout<<"Value of a is : "<<*p1<<endl; cout<<"Value of b is : "<<*p2<<endl; //swap temp = *p1; *p1 = *p2; *p2 = temp; cout<<"\nAfter swapping two Numbers.\n"; cout<<"Value of a is : "<<*p1<<endl; cout<<"Value of b is : "<<*p2<<endl; getch(); }
Output:
Another Program: Write a C++ Program to display Box shape using for loop.
Pingback: Write a C++ program to read age of 15 people and count total Baby age, School age and Adult age.