How to swap two numbers without using a temporary variable using C program?
C program to swap two integer numbers without using temporary variable: Here, we will learn how to swap numbers without taking help of another variable in C?
Given two integer numbers "a" and "b" and we have to swap their values without using any temporary variable.
Input: a=10, b=20 Output: a=20, b=10
Logic to swap number using temporary variable:
In this program, we are writing code that will swap numbers without using other variable.
To swap numbers:
Step 1) Add the value of a and b and assign the result in a.
a = a+b;
Step 2) To get the swapped value of b: Subtract the value of b from a (which was the sum of a and b).
b = a-b;
Step 3) To get the swapped value of a: Subtract the value of b from a.
a = a-b;
These are the above written three statements to swap two numbers:
//swapping numbers a = a+b; //step 1 b = a-b; //step 2 a = a-b; //step 3
Let’s understand with the values:
Input: a=10 and b=20 Step1: a = a+b → a= 10+20 → a=30 Now: a=30 and b=20 Step2: b = a-b → a= 30-20 → b=10 Now: a=30 and b=10 Step3: a = a-b → a= 30-10 → a=20 Now: a=20 and b=10 Values are swapped now, Output: a=20 and b=10
Program to swap numbers without using temporary variable in C
In first run, the input values of a and b are 10 and 20 respectively, after swapping values of a and b are 20 and 10 (swapped values).
Same as second run, the input values of a and b are -100 and -200 respectively, after swapping values of a and b are -200 and -100 (swapped values).need an explanation for this answer? contact us directly to get an explanation for this answer