• Post author:
  • Reading time:2 mins read
  • Post category:Programming

Programming pre-requisites to swap two numbers in c


c program to swap two numbers using temporary variable

#include<stdio.h>
int main(int argc, char const *argv[])
{
	int number1,number2,temp;
	printf("\nSwapping of two numbers in c\nEnter two numbers \n");
	scanf("%d%d",&number1,&number2);
	printf("Number 1: %d\nNumber 2: %d",number1,number2);
	//swapping
	temp=number1;
	number1=number2;
	number2=temp;
	printf("\nAfter swapping");
	printf("\nNumber 1: %d\nNumber 2: %d\n",number1,number2);
	return 0;
}
C Program to swap two numbers
C Program to swap two numbers

C Program to swap two numbers without third variable by Addition and subtraction

#include<stdio.h>
int main(int argc, char const *argv[])
{
	int number1,number2;
	printf("\nSwapping of two numbers in c\nEnter two numbers \n");
	scanf("%d%d",&number1,&number2);
	printf("Number 1: %d\nNumber 2: %d",number1,number2);
	//swapping
	number1=number1+number2;
	number2=number1-number2;
	number1=number1-number2;
	printf("\nAfter swapping");
	printf("\nNumber 1: %d\nNumber 2: %d\n",number1,number2);
	return 0;
}
Swapping of two numbers in c

C Program to swap two numbers without third variable by Multiplication and Division

#include<stdio.h>
int main(int argc, char const *argv[])
{
	int number1,number2;
	printf("\nSwapping of two numbers in c\nEnter two numbers \n");
	scanf("%d%d",&number1,&number2);
	printf("Number 1: %d\nNumber 2: %d",number1,number2);
	//swapping
	number1=number1*number2;
	number2=number1/number2;
	number1=number1/number2;
	printf("\nAfter swapping");
	printf("\nNumber 1: %d\nNumber 2: %d\n",number1,number2);
	return 0;
}
Swapping of two numbers in c

C Program to swap two numbers without third variable by Xor operation

#include<stdio.h>
int main(int argc, char const *argv[])
{
	int number1,number2;
	printf("\nSwapping of two numbers in c\nEnter two numbers \n");
	scanf("%d%d",&number1,&number2);
	printf("Number 1: %d\nNumber 2: %d",number1,number2);
	//swapping
	number1=number1^number2;
	number2=number1^number2;
	number1=number1^number2;
	printf("\nAfter swapping");
	printf("\nNumber 1: %d\nNumber 2: %d\n",number1,number2);
	return 0;
}
Swapping of two numbers in c