Basics of C Programming

⯈Basic C Programs

C Program to swap two numbers

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

If we write, a = b, then the value of a will be over-written with ‘b’. A variable can store only one value at a given point of time.

swap two numbers

Since the value of ‘a’ is formatted with the value of ‘b’, before we format, we should store the value of ‘a’ in some variable.

So we write,

temp = a; (store a in temp, before we format)

swap two numbers

Now we can over-write a,
a = b

swap two numbers

After we swap, the value of 'b' has to be 5, therefore,
temp = b

swap two numbers


temp = a;
a = b;
b = temp;

C program

int main()
int a, b;
int temp;

printf("Enter two numbers:");

temp = a;
a = b;
b = temp;

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

return 0;

Output window of above code

swap two numbers
Scroll to Top