# C program to swap two numbers (Without using a temporary variable)

## Introduction

In this program, you will learn to swap two numbers in the C language using logic of addition and subtraction.

To understand this program, you should know about

1. C Data types

2. C programming operators

## Program

```#include<stdio.h>

int main()

{

float a,b;

printf("Enter two numbers:\n");

scanf("%f %f",&a,&b);

printf("Before swaping numbers are:\na=%f\nb=%f",a,b);

//swapping

a=a-b; // (a'=original_a-original_b)

b=a+b; // (b'=a'+original_b)

a=b-a; // (a''=b'-a')

printf("\nAfter swaping numbers are:\na=%f\nb=%f",a,b);

return 0;

}```

## Explanation

In the above program, the user is asked to enter two values.

The user enters a=87 and b=45.

Let’s understand the above logic

a=a-b; suppose we are assigning the subtracted value i.e., 87-45=42 to a variable a’.

a’=42. Now, this is the updated value of ‘a’ and will be used in the further code.

b=a+b; ‘b’ is still 45 but ‘a’ is 42 therefore we get 45+42=87. Consider b’=87

b’=87 Now this is the updated value of ‘b’ and will be used in the further code.

a=b-a; here we will use the updated value of ‘a’ and ‘b’. 87-42=45

Therefore, the final value of ‘a’ and ‘b’ is 45 and 87, respectively.

Since values were declared as float, that’s why we have float values in the output.

## Author

• A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.