Object
Write a program that swaps two values using pointers.
Algorithm
- Declare a function void swap(int *x, int *y) that accepts two integer pointer arguments and returns no value.
The Function main - Declare integer variables a and b.
- Set a = 10 and b = 20.
- Write values of a and b.
- Call the function swap(&a, &b) considering a and b as actual arguments.
- Write swapped values of a and b.
- Exit.
Defining the Function void swap(int *x, int *y)
where *x and *y are the formal integer pointer arguments - Declare integer variable temp.
- temp = *x.
- *x = *y.
- *y = temp.
- Exit.
Flowchart

C++ Source Code
// program 103
#include<iostream>
using namespace std;
void swap(int *x, int *y);
int main()
{
int a = 10, b = 20;
cout << "Values of a and b before swapping are: " << endl;
cout << "a = " << a << " and b = " << b << endl;
swap(&a, &b);
cout << "\nValues of a and b after swapping are: " << endl;
cout << "a = " << a << " and b = " << b << endl;
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
C Source Code
/*program 103*/
#include<stdio.h>
void swap(int *x, int *y);
int main()
{
int a = 10, b = 20;
printf("\nValues of a and b before swapping are: ");
printf("\na = %d and b = %d", a,b);
swap(&a, &b);
printf("\n\nValues of a and b after swapping are: ");
printf("\na = %d and b = %d", a,b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output
Values of a and b before swapping are:
a = 10 and b = 20
Values of a and b after swapping are:
a = 20 and b = 10
