Algorithm
Process 1: Using a temporary variable.
- Take two numbers
- First make a temporary variable, called
temp
. - Assign temp to
x
- Update
x
toy
- and
y
totemp
- Print x and y and now they are swipped.
Code Examples
#1 Example with Temporary third Variable
Code -
C Programming
#include<stdio.h>
int main()
{
int x = 20, y = 30, temp;
temp = x;
x = y;
y = temp;
printf("X = %d and Y = %d", x, y);
return 0;
}
Copy The Code &
Try With Live Editor
Output
X = 30 and Y = 20
#2 Example with number input variables
Code -
C Programming
#include<stdio.h>
int main()
{
int x, y, temp;
printf("Please enter number 1:");
scanf("%d", &x);
printf("Please enter number 2:");
scanf("%d", &y);
temp = x;
x = y;
y = temp;
printf("X = %d and Y = %d", x, y);
return 0;
}
Copy The Code &
Try With Live Editor
Input
Please enter number 1: 40
Please enter number 2: 50
Please enter number 2: 50
Output
X = 50 and Y = 40
Demonstration
It's just swapping numbers.
Using temporary variable it's simple. Just make a temporary variable and assign one to another.
temp = x;
x = y;
y = temp