Write a program to swap two numbers in C [with or without 3rd variable]

Today, we learn about swapping of two numbers in c using the 3rd variable and without using a 3rd variable.

Swapping of two numbers in C using 3rd variable

#include<stdio.h>
#inclue<conio.h>

void main()
{
int a,b,c;
clrscr();
printf("Enter 1st number:");
scanf("%d",&a);
printf("Enter 2nd number:");
scanf("%d",&b);
//Swapping method using 3rd variable
c=a;
a=b;
b=c;
printf("After swapping, new values\n");
printf("a=%d",a);
printf("\nb=%d",b);
getch();
}

Programme Code Explanation(PCE)

In the above programming code, we are swapping of two numbers in C with a 3rd variable.

We need 3 different variables from which 2 (a,b) to get values from user and 1 (c) is used to swap values from one variable to another.

swapping of two numbers in c

Swapping of two numbers in C without 3rd variable

#include<stdio.h>
#inclue<conio.h>

void main()
{
int a,b,c;
clrscr();
printf("Enter 1st number:");
scanf("%d",&a);
printf("Enter 2nd number:");
scanf("%d",&b);
//Swapping method without using 3rd variable
a=a+b;
b=a-b;
a=a-b;
printf("After swapping, new values\n");
printf("a=%d",a);
printf("\nb=%d",b);
getch();
}

Programme Code Explanation(PCE)

In the above program code, we have done swapping of two numbers in C without using a 3rd variable.

You can see in the above code, we do not use the 3rd variable for swapping. Only we add both given values then subtract one by one from that added value.

If we use a=a+b; it means you are adding values of both ‘a’ and ‘b’ and transferring result again into ‘a’ variable.

Then, b=a-b; it subtracts the old value of ‘b’ from the new value of ‘a’. Again apply a=a-b; transfers the resultant value into ‘a’ variable.

Hope that you all understand swapping of two numbers in c. It is a beginner lever programming code but many times, this question asked in interviews and other exams.

Other useful links

If you have questions please comment me in below comment section. Don’t forget to share this code in your class. You can also read my other tech blog zerootech.com

Leave a Comment

error: Don\'t make piracy - Write your own content :)