GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

Algorithm to swap two numbers without using extra variable

In the previous section, we have seen how to swap two integer numbers using extra variable. In this section we will see how we swap two numbers without using extra variable.

Let the two numbers be A and B.

Let A = 10 and B =20.

swap without extra variable

We add the values of A and B. Since we cannot use an extra variable, the sum has to be stored either in A or B. Let us store the answer (A+B) in A.

A = A + B (read as, A is assigned with the value of A + B, compute A + B and store in A)

swap two numbers without extra variable

A = A + B, evaluate the RHS first,

the answer 10 + 20 = 30, is stored in A. The previous value of A (10) is overwritten. 

Note: A variable can store only one value at a given point of time.

Now the question is, can we get back the value 10, which is lost. Definitely yes and you guessed it right.

We subtract B from A to get back 10. (A = 30 and B = 20, the recent values). The value 10 after swapping we want to store in B,

Therefore, we write.

B = A – B [read as compute A – B and store in B] 

swap two numbers without using extra variable

At the last we need to get back 20, which we want to store in A. And we get 20 as,

A = A – B [read as compute A – B and store in A]

swap two numbers without using extra variable

At end, we see that the values of A and B are swapped.

Algorithm:

Name of Algorithm: Swap two numbers

Step 1: Start

Step 2: Read two numbers as A and B

Step 3: A = A + B

             B = A – B

             A = A – B

Step 4: Display A and B

Step 5: Stop

In the next section, we shall discuss the basics of C programming language.

Scroll to Top