Pointer Program #3
12. Swap two numbers using user defined function. (Use concept of Call by Reference).
#include<stdio.h>
void swap(int *,int *);
void main()
{
int x,y;
printf("Enter the values of first number:\n");
scanf("%d",&x);
printf("Enter the values of second number:\n");
scanf("%d",&y);
swap(&x,&y);
printf("\nValues inside the main function:");
printf("\nfirst=%d,second=%d\n",x,y);
}
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf("\nValues inside the swap function:");
printf("\nfirst=%d,second=%d",*a,*b);
}
void swap(int *,int *);
void main()
{
int x,y;
printf("Enter the values of first number:\n");
scanf("%d",&x);
printf("Enter the values of second number:\n");
scanf("%d",&y);
swap(&x,&y);
printf("\nValues inside the main function:");
printf("\nfirst=%d,second=%d\n",x,y);
}
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf("\nValues inside the swap function:");
printf("\nfirst=%d,second=%d",*a,*b);
}
Output
- Enter the values of first number:
3
Enter the values of second number:
5
Values inside the swap function:
first=5,second=3
Values inside the main function:
first=5,second=3
Note:
Call by reference
- In call by reference, the address of actual parameters are passed as an argument to the called function.
- So the original content of the calling function can be changed.
- Call by reference is used whenever we want to change the value of local variables through function.
Comments
Post a Comment