Program to swap two numbers using pointers is a simple and easy program to swap two numbers using pointers in c.

Pointers in c
The pointer is a variable that stores address of another variable.
syntax for pointers in c
<Datatype> *pointername;
Example:- int *ptr;

Accessing the value of the variable:-
& Address of the operator gives the address of the variable.
* gives the value at that address stored in the pointer variable.

How to swap two numbers using pointers
We take two inputs from a user and pass the address of numbers to function. Using * (value at address) operator function swaps two numbers and print numbers after swapping.

Algorithm to swap two numbers using pointer

  1. Declare variable
  2. Take two numbers input
  3. Pass address to function
  4. Write a function which accepts the address of both numbers
  5. In function using * swap two numbers
  6. Print numbers after swapping

Program to swap two numbers using pointers

#include<stdio.h>
void swap(int *,int*);
main( )
{
int a,b;
printf("Enter a and b values\n");
scanf("%d%d",&a,&b);
printf ("Values before Swap\na=%d\nb=%d\n",a,b ) ;
swap(&a,&b ) ;
printf ("Values after Swap\na=%d\nb=%d\n",a,b ) ;
}
void swap( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}

Output :

swap two numbers using pointers

Write A Comment