Write a program in C to swap elements using call by reference

Previous
Next

Solution:

  • Swapping is the concept of interchanging the values of 2 numbers.
  • We use call by reference concept to swap 2 numbers in this code.
  • Read elements into variables a and b in main() function and pass the addresses of these variables to swap() function.
  • We collect these references into pointer type arguments in Called function.
  • When we process the values in the called function using pointer variables, it swaps the data in calling function variables a and b.
#include<stdio.h>
void swap(int*,int*);
void main()
{
	int a, b;
	printf("Enter two numbers\n");
	scanf("%d%d", &a, &b);
	printf("Before swap : \t%d\t%d\n",a,b);
	swap(&a,&b);
	printf("After swap in main() function : \t %d \t %d \n",a,b);
}
void swap(int* x, int* y)
{
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
	printf("After swap in swap() function : \t %d \t %d \n",*x,*y);	
}
Previous
Next

Courses Enquiry Form