Swapping

C Programming

C Programming Examples

#include<stdio.h>

/* Function 'swap' with pointer parameter */
void swap(int *a, int *b) {
	int temp;

	/* Swapping values using 'temp' variable */
	temp = *a;
	*a = *b;
	*b = temp;
}

int main() {
	int x, y;
	printf("Enter a value for X:\n");
	scanf("%d", &x);
	printf("Enter a value for Y:\n");
	scanf("%d", &y);
	printf("Before swapping\n");
	printf("X = %d\nY = %d\n",x, y);

	/* Passing reference(memory address) of the variables */
	swap(&x, &y);
	printf("After swapping\n");
	printf("X = %d\nY = %d\n",x, y);
	return 0;
}


          /****** Output ******/
          

Enter a value for X:


5


Enter a value for Y:


10


Before swapping


X = 5


Y = 10


After swapping


X = 10


Y = 5

Learn more about Call by reference