C Program to Swap Two Numbers Without a Third Variable

The program to swap two number uses simple procedure with fewer number of variables.

The regular swapping procedure contains an extra variable called temp, a temporary variable to hold values in between the swap task. This program does not use any temp variable and achieve the same results.

We wrote the program with Dev-C++ version 4 compiler installed on a Windows 7 64-bit PC.  If you may try another standard C compiler, like Turbo C++ 3.0, then modify the source code according to the compiler specifications.

Learn following c programming concepts before you try this example program. If you know the concepts already, then continue reading the article.

Problem Definition

The following code shows the common method to swap two integer numbers within a C program. As mentioned earlier, it uses a temp variable.

The temp is assigned the value of variable a and a is assigned the value of variable b.

temp is 10

a is 20.

In the next step, b is assigned the value of temp to complete the swap procedure.

b = temp;

b is 10 now.

a = 10    b = 20    temp = a; /* Store the value of variable a into temp */    a = b; /* Value of b is assigned to a */    b = temp; /* Value of temp is assigned to b*/

Flowchart – Swap Numbers without Third Variable

Flowchart - Swap two numbers without third variable
Flowchart – Swap two numbers without third variable

Program Code – Swap Numbers without Third Variable

/* Program to swap two numbers without a third variable */    #include <stdio.h>  #include <conio.h>    int main()  {        int a,b; int i;        /* Read two numbers */        printf("Enter value for A:");      scanf("%d",&a);        printf("Enter value for B:");      scanf("%d",&b);        /*Swap the Variables with out a third variable*/        a = a + b;      b = a - b;      a = a - b;        /* Print the result */        for(i=0;i<35;i++)      printf("_");printf("\n\n");        printf("A = %d B = %d\n\n",a,b);        for(i=0;i<35;i++)      printf("_");printf("\n\n");        getch();      return 0;  }  

The above source code shows efficient use of arithmetic operators to swap the number and moreover, it is faster because there is no unnecessary assignments of variables.

Output

Output-Swap without a third variable
Output-Swap without a third variable

Related Articles:

Advertisements


Advertisements