WEB DEVELOPER SITE

# Swap Two Numbers using Temporary Variable C++ Tutorial

Following is the program to swap two numbers with the help of a temporary variable.

```#include<iostream.h>
#include<conio.h>

int main()
{
int a,b,x;

cout<<"Enter a and b:\n";
cin>>a>>b;
cout<<"Before swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b= "<<b<<endl;
{
x=a;
a=b;
b=x;
cout<<"After swapping"<<endl<<"Value of a= "<<a<<endl<<"Value of b= "<<b<<endl;
}
getch();
return 0;
}

Output:

Enter a and b:
23
45
Before swapping
Value of a= 23
Value of b= 45
After swapping
Value of a= 45
Value of b= 23

Swap Two Numbers without using Temporary Variable
#include <stdio.h>
int main()
{
double firstNumber, secondNumber;

printf("Enter first number: ");
scanf("%lf", &firstNumber);

printf("Enter second number: ");
scanf("%lf",&secondNumber);

// Swapping process

firstNumber = firstNumber - secondNumber;
secondNumber = firstNumber + secondNumber;
firstNumber = secondNumber - firstNumber;

printf("\nAfter swapping, firstNumber = %.2lf\n", firstNumber);
printf("After swapping, secondNumber = %.2lf", secondNumber);

return 0;
}

Output

Enter first number: 10.25
Enter second number: -12.5

After swapping, firstNumber = -12.50
After swapping, secondNumber = 10.25

output
Enter case:
3
Enter the order of matrix a (must be m*n):
2
*
3
Enter the order of matrix b (must be o*p):
3
*
4
Multiplication possible
Enter the elements of matrix 1:
1 2 3 4 5 6
Elements of matrix 1 are:
1 2 3
4 5 6
Enter the elements of matrix 2:
1 2 3 4 5 6 7 8 9 10 11 12
Elements of matrix 2 are:
1 2 3 4
5 6 7 8
9 10 11 12
Multiplication:
c=aXb=
38 44 50 56
83 98 113 128

« Previous
Next Chapter »

```