Develop an algorithm and C program to swap two values using a temporary variable.
5 marks
Answer in brief
Swapping means exchanging the values of two variables. A temporary variable holds one value while the exchange takes place.
Algorithm
Save the first value: Set temporary = a.
Replace the first value: Set a = b.
Restore the saved value: Set b = temporary.
Display a and b: They now contain the exchanged values.
Explanation with an example
Suppose a = 12 and b = −5. First, temporary receives 12. Next, a receives −5. Finally, b receives the saved 12. The final values are a = −5 and b = 12. After the second statement, both a and b briefly contain −5, but the old value 12 is still safe in temporary.
Need for the temporary variable
If we first write a = b, the old value of a is overwritten. We cannot copy it into b afterward unless it was saved. The temporary variable prevents this loss. Assignment copies a value; it does not permanently connect the variables. Changing a later does not automatically change temporary.
Important points
Use a temporary variable of a suitable type. The same three steps work for negative values and equal values. This method is clearer than addition-and-subtraction swapping, which may overflow during an intermediate calculation. If a swap is placed inside a function, additional care is needed to change the caller’s variables; ordinary value parameters are copies.
Time and space complexity
There are three assignments and one extra temporary variable. These do not grow with the input values, so time and extra space are both O(1).
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a = 12, b = -5;
int temporary = a;
a = b;
b = temporary;
printf("a = %d, b = %d\n", a, b);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
a = -5, b = 12
Key points
Save a value before overwriting it.
The temporary variable should have a compatible type.