Swapping Two Numbers Using Variable in C



In many case, programmers are required to swap values of two variables. Here, we shall learn how to swap values of two integer variables, that may lead to swapping of values of any type. Values between variables can be swapped in two ways −

  • With help of a third (temp) variable
  • Without using any temporary variable

We shall learn the first method here to see the second method click here.

Algorithm

Lets find out how should we draw a solution step-by-step −

START
   Var1, Var2, Temp
   Step 1 → Copy value of Var1 to Temp
   Step 2 → Copy value of Var2 to Var1
   Step 3 → Copy value of Temp to Var2
STOP

Pseudocode

From the above algorithm, we can draw pseudocode for this program −

procedure swap(a, b)
   
   set temp to 0
   temp ← a
   a ← b      // a holds value of b
   b ← temp   // b holds value of a stored in temp

end procedure

Implementation

C implementation of the above algorithm should look like this −

#include <stdio.h>

int main() {
   int a, b, temp;

   a = 11;
   b = 99;

   printf("Values before swapping - \n a = %d, b = %d \n\n", a, b);

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

   printf("Values after swapping - \n a = %d, b = %d \n", a, b);
}

Output

Output of this program should be −

Values before swapping -
 a = 11, b = 99                                         
 
Values after swapping -
 a = 99, b = 11
simple_programs_in_c.htm
Advertisements