Write a C program to swap the two values using pointers
- Program:
#include<stdio.h>#include<conio.h>void main(){//Declaration of variables and pointer variablesint x,y,*ptr_x,*ptr_y,temp;//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:
Enter the value of x and y 100 123 Before Swapping x = 100 y = 123 After Swapping x = 123 y = 100
We ask the user to enter values for variable a and b. We pass the address of variable a and b to function swap().
Inside function swap() we take a local variable temp. Since address of variable a and b are passed to swap() method, we take 2 pointer variables *x and *y. Pointer variable x holds the address of a and pointer variable y holds the address of b. Using below logic we swap the values present at address a( or x ) and b( or y ).
temp = *x;
*x = *y;
*y = temp;
Since we are directly changing the value present at particular address, the value gets reflected throughout the program and not just inside particular function. That’s why we are able to print the result inside main function and the values of variable a and b are swapped, without getting any returned value from function swap().
- Program:
#include<stdio.h>#include<conio.h>void swap(int*, int*);int main(){int a, b;printf("Enter the value for a and b\n");scanf("%d%d", &a, &b);printf("\n\nBefore swapping: a = %d and b = %d\n",a, b);swap(&a, &b);printf("\nAfter sawpping: a = %d and b = %d\n", a, b);return 0;}void swap(int *x, int *y){int temp;temp = *x;*x = *y;*y = temp;}
- Output:
Enter the value for a and b 100 200 Before swapping: a = 100 and b = 200 After sawpping: a = 200 and b = 100
- Visit:
0 comments