C program to swap value of two given numbers.

Problem statement

Write a C program to take two numbers as input from user and stored them in two different variables. Then they interchange the value with each other using third variable.

Program of swapping

Output

Explanation

Swapping means interchanging the values.
Firstly we take two values from user and stored them into two variables num1 and num2 respectively.
Now we also use third temporary variable temp.
First of all, we store value of num1 into temp variable and value of num2 into num1.
In this way value of the second variable is stored in the first variable.
And lastly, we transfer value of temp into num2.
Therefore we swap the values of two variables using third variable.

 
 
 

Write a program to swap two numbers without using third variable

Output

Explanation:

First of all, we take two values i.e, 20 and 50 as input from user and stored them into two variable num1 and num2 respectively.
Now see how these following statements interchange the values,
num1 = num1 + num2
  = 20 + 50
num1 = 70
——————————-
num2 = num1 – num2;
= 70 – 50
num2 = 20
——————————-
num1 = num1 – num2;
= 70 – 20
num1 = 50

In this way, we swap the values of two variables without using the third variable.

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.