this Program to swap Two Numbers Using Pointer
#include "stdafx.h"
# include <iostream>
using namespace std;
void p_swap(int *pNum1, int *pNum2);
int main(void)
{
int num1=0, num2=0;
cout << "Enter two numbers to swap between them: " << endl << "Number (1): ";
cin >> num1;
cout << "Number (2): ";
cin >> num2;
p_swap(&num1, &num2 ); //pass the addresses
cout<< endl<< "After the swap, number1 is " << num1 << endl<< " number2 is " << num2 << "."<< endl;
system ("pause");
return 0;
}
//-------------- Function to reverse two values
void p_swap(int *pNum1, int *pNum2) // receiving addresses not values
{
int temp; // temporary holding variable
temp = *pNum1; // swap the values stored at the addresses
*pNum1 = *pNum2;
*pNum2 = temp;
return; // main( )'s variables, not copies of them, have been changed
}
No comments:
Post a Comment