Swapping of two numbers

Posted

in

by

Tags:

Before Swapping :
a = 10
b = 2

After Swapping:
a = 2
b = 10

To do the swapping we have different approaches.
1. Swapping using a temporary variable
2. Swapping without using a temporary variable
3. Swapping using pointers

NOTE: We do not use of the second method in embedded system software writing. Because it would have to execute more instructions to perform the same operation with a temporary variable.

Swapping using a temporary variable

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	int a = 10;
	int b = 3;
	int temp = 0;
	printf("Before Swapping");
	printf("\na = %d\tb = %d\n",a,b);

	temp = a;
	a = b;
	b = temp;

	printf("After Swapping");
	printf("\na = %d\tb = %d\n",a,b);

	return EXIT_SUCCESS;
}

Swapping without using a temporary variable

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	int a = 10;
	int b = 3;
	int temp = 0;
	printf("Before Swapping");
	printf("\na = %d\tb = %d\n",a,b);

	a = a - b;
	b = a + b;
	a = b - a;

	printf("After Swapping");
	printf("\na = %d\tb = %d\n",a,b);

	return 1;
}

Swapping using pointers

When the memory size is very limited we prefer to do this.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	int a = 10;
	int b = 3;
	int temp;
	int *x , *y;

	printf("Before Swapping");
	printf("\na = %d\tb = %d\n",a,b);

	x = &a;
	y = &b;
	temp = *x;
	*x = *y;
	*y = temp;

	printf("After Swapping");
	printf("\na = %d\tb = %d\n",a,b);
	
	return 1;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *