# C Programming – Swap function using Pointers , pass by address

To learn basics of pointer & pointer arithmetic concepts, refer tutorial Array and Pointers Arithmetic in C Programming – Examples

Swap is function to exchange or interchange the values of two variables. This function interchange the value of two variable using temporary variable.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include<stdio.h> void swap(int *p,int *q) { int t; t=*p; *p=*q; *q=t; } int main() { int x=100,y=200; printf("\nBefore swap value of x= %d value of y is %d\n",x,y); swap(&x,&y); //pass by address printf("\nAfter swap value of x= %d value of y is %d\n",x,y); printf("\n----------------------------------digitalpadm.com\n\n"); return 0; } |

In this code,

Step-1: In main function, x and y are integer type variables are initialized to 100 and 200 respectively,

Step-2: display the values of x and y before swap function call.

Step-3: swap function is called, address of x and y are send as parameter.

Step-4: In swap function, these addresses are placed in pointer variable p and q, i.e pointer variable p holds the address of x variable and pointer variable q holds the address of y variable.

Step-5: In swap, t is temporary variable,

`t= *p;`

*p gives the value stored at variable x, which is 100 and assigns to variable t.

`*p=*q;`

*q gives the value stored at variable y, which is 200 and assigns to `*p`

, i.e as value for variable x becomes 200

`*q=t; `

assign the value of t to variable , which is 100 to `*q`

, i,e as value of for y variable becomes 100

step-6: In main function, display the values of x and y again, which is interchanged.

###### OUTPUT

Download Code : C Programming - Swap function using Pointers working (8 downloads)