Skip to study material
← Question index

QUESTION 20 · Worked algorithms

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

  1. Save the first value: Set temporary = a.
  2. Replace the first value: Set a = b.
  3. Restore the saved value: Set b = temporary.
  4. 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).

Reference table

↔ Scroll horizontally on a small screen
State during the swap
After statementabtemporary
temporary = a12-512
a = b-5-512
b = temporary-51212

Diagram or flowchart

Save a in temporary, assign b to a, then assign temporary to b; finally print the swapped values.
Swapping with a temporary variable · Download diagram

C program and output

/* 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.