Swapping Two Numbers
C Programming Language

C Program for Swapping two Numbers 2022

Today, we are here to teach you how to write a C Program that will Swapping Two Numbers. Swapping means exchanging the value of two variables. And if you are Computer Science or Software engineering Student, then you should be excited to know that you are in right place. We will teach you each and everything about coding.

Swapping Two Numbers

Swapping Two Numbers is much easier in C language, however, it is also easy in C++ and other languages. Previously, we published an article which is about Best C Program to Swap Two Numbers Using Functions 2022  but in this article, we will show you how simple we can swap two numbers without functions.

You can also swap the value of two variables by using functions. if your teacher’s requirement is to swap two numbers by functions or it can be swap two numbers using pointers, then you have to do as your question is. but if you have to swap two numbers simply, then you can use this method of swapping.

Program

Write an Easy Program in C that will Swap two Numbers.

#include<stdio.h>
int main()
{
    int a,b,temp;
    printf("enter the value of a and b: \n");
    scanf("%d %d",&a,&b);
    printf("value of a=%d and b=%d before swapping\n",a,b);
    temp=a;
    a=b;
    b=temp;
    printf("value of a=%d and b=%d after swapping\n",a,b);
}

Output

The above program will print and swap the value of two numbers. First of all, we have to take three integer-type variables which are a,b and temp. We will take the value of a and b from the user. The values will be swapped. Then we have taken the third variable called temp.

We have taken the third variable because, without the third variable, we cannot swap the value of a and b. After taking values from the user, we have applied conditions in which the first is temp=a, Which means that the value of a is passed to temp and now a is empty.

Then another condition a=b, which means that the value of b is passed to a and now b is empty. then we have applied another condition which is b=temp, which means that the value of temp is passed to b. as the temp is holding the value of a and now that value is given to b.

Conclusion

From the above program, we concluded that there is a very easy and simple way for Swapping Two Numbers.  You can also swap the values of two variables by taking integer-type variables of your own choice. You can also use this method of swapping in c++ and other languages.

Leave a Reply

Your email address will not be published. Required fields are marked *