Home Misc Write a program to swap 2 numbers.

Write a program to swap 2 numbers.

by nikoo28
0 comment

Question: Write a program to swap 2 numbers?

Input: a = 4, b = 19
Output: a = 19, b = 4

Swapping 2 numbers is one of the most basic tasks while programming. But sometimes, we tend to make error in it. For instance look at this code.

// function to swap 2 integers
void swapIntegers(int a, int b)
{
	// create a temporary variable and interchange the values
	int temp = a;
	a = b;
	b = temp;

    printf("\nI am inside function\n");
	printf("a = %d\n",a);
	printf("b = %d\n",b);
}

// driver program to test the above function
int main(void)
{
	int a = 4;
	int b = 15;
	
	// printing the values
	printf("a = %d\n",a);
	printf("b = %d\n",b);

    printf("\nI am calling the function\n");
	
	// calling the swap function
	swapIntegers(a,b);

    printf("\nI am out of the function\n");
	
	// printing the values
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	
	return 0;
}

The output of the above program is:-

a = 4
b = 15

I am calling the function

I am inside function
a = 15
b = 4

I am out of the function
a = 4
b = 15

What happened? The values were changed inside the function but the changes did not reflect when returning. This is because when we call the function swapIntegers(int, int), only the value of the integers is passed. As the function finishes, their scope is lost.

To overcome this problem we need to pass the references of the values.

// function to swap 2 integers
void swapIntegers(int * a, int * b)
{
	// create a temporary variable and interchange the values
	int *temp = *a;
	*a = *b;
	*b = temp;
	
	printf("\nI am inside function\n");
	printf("a = %d\n",*a);
	printf("b = %d\n",*b);
}

// driver program to test the above function
int main(void)
{
	int a = 4;
	int b = 15;
	
	// printing the values
	printf("a = %d\n",a);
	printf("b = %d\n",b);

    printf("\nI am calling the function\n");
	
	// calling the swap function by passing reference
	swapIntegers(&a,&b);

    printf("\nI am out of the function\n");
	
	// printing the values
	printf("a = %d\n",a);
	printf("b = %d\n",b);
	
	return 0;
}

The output will now be:-

a = 4
b = 15

I am calling the function

I am inside function
a = 15
b = 4

I am out of the function
a = 15
b = 4

You can also check out all the different methods to swap 2 integers in this post.

You may also like

Enclose codes in [code lang="JAVA"] [/code] tags

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More