Basics of C Programming

⯈Basic C Programs

C Program to swap two numbers without using extra variable

We start the programs, by reading the input. The input to the program is two numbers. Let the two numbers be ‘a’ and ‘b’ of type integer. 

Input: ‘a’ and ‘b’ (int)

Output: Swapped values of ‘a’ and ‘b’

Reading input,


Let a = 5 and b = 7

swap two numbers

We add the values of a and b, and we cannot use the temporary variable, so we add the values of a and b and we need to store the answer either in a or b.

a = a + b;
swap two numbers

The value of ‘a’ is over-written with the new value 12. The value 5 is lost. Can we get 5 back? Yes, of course we can!

We subtract the values of b from a,

a = 12, and b = 7

a – b = 5. 

After we swap the values of a and b, we want to store the value 5 in variable b. Therefore we write,

b = a - b;
swap two numbers

We want to store 7 in variable a. Can we get 7 from 12 and 5, Yes, you guessed it right! You are a pro now 🙂

we write,

a = a - b;
swap two numbers

At the end we print the values of a and b,

printf("a = %d\n b = %d\n",a,b);

C Program

int main()
int a, b;
printf("Enter two numbers:");

a = a + b;
b = a - b;
a = a - b;

printf("a = %d\nb=%d\n",a,b);
return 0;

Output window

swap two numbers
Scroll to Top