program to swap two number by using pointer in c-programming
In this program ,we will now swap two number by using pointer in c-program by taking input form the user.
When we call the function, we pass the address of the variable, so this method is called “Call by Reference“.
when we ask the user to enter the values for variable a and b. We passes the address of variable a and b to the function swap().
Inside the function swap() we take a local variable i. Since address of variable a and b are passed to swap() function , 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 ).
#include<conio.h>
int swap(int *,int *);
void main()
{
int a,b;
printf("enter the two number:-");
scanf("%d %d",&a,&b);
printf("\nbefore swapping:- a=%d and b=%d",a,b);
swap(&a,&b);
printf("\nafter swapping:- a=%d and b=%d",a,b);
getch();
}
int swap(int *x,int *y)
{
int i;
i=*x;
*x=*y;
*y=i;
}
output:-
For more c-programming:-

No comments:
Post a Comment