C Program to Swap Two Numbers Without a Third Variable

The program to swap two number uses the simple procedure with a 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.

Advertisements

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.

Advertisements
\begin{aligned}
&temp = 10\\ \\
&a = 20
\end{aligned}

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

\begin{aligned}
&b = temp;\\ \\
&b \hspace{2mm} is \hspace{2mm} 10 \hspace{2mm}now.
\end{aligned}

Code For Swap Using A Temp Variable

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

Flowchart – Swap Numbers without Third Variable

Flowchart - Swap two numbers without third variable
Figure 1 – Flowchart of Swap two numbers without third variable

Program Code – Swap Numbers without Third Variable

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

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

Output

Enter value for A:24
Enter value for B:44
----------------------------------------
A = 44 B = 24
----------------------------------------

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.