# Write a C program to swap the two values using pointers

0 like 0 dislike
765 views

Write a C program to swap the two values using pointers

## 1 Answer

0 like 0 dislike
by Goeduhub's Expert (7.1k points)
edited

Best answer

Swapping of Two Numbers Using Pointers

In this program we are going to swap two numbers using pointers. The pointer will be used to hold the address of the variable and using pointer address of the variables will be swepped. In the following example we are going to implement this theory.

Example :

 #include#include    void main(){//Declaration of variables and pointer variablesint x,y,*ptr_x,*ptr_y,temp;clrscr();    //Insert value of x and yprintf("Enter the value of x and y\n");scanf("%d%d", &x, &y);//Printing value before swappingprintf("Before Swapping\nx = %d\ny = %d\n", x, y);//Assigning address of variables to pointersptr_x = &x;ptr_y = &y;//Swapping pointer address with the help of temp variabletemp = *ptr_y;*ptr_y = *ptr_x;*ptr_x = temp;//printing values of x and yprintf("After Swapping\nx = %d\ny = %d\n", x, y);getch();}

Output : Add Two Numbers Using Pointers

In this program we are going to add two numbers using pointers

Example :

 #include#includevoid main(){int a,b,sum=0;//pointers pointing at a and bint *ptr_a=&a,*ptr_b=&b;clrscr();printf("Enter a and b:");scanf("%d%d",&a,&b);//sum of a and b using pointerssum=*ptr_a+*ptr_b;printf("\nSum = %d",sum);getch();}

Output : 