Swapping Two Numbers Program in C Language with Full explanation and algorithm

Algorithm


Process 1: Using a temporary variable.

  1. Take two numbers
  2. First make a temporary variable, called temp.
  3. Assign temp to x
  4. Update x to y
  5. and y to temp
  6. 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
+
cmd
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

x
+
cmd
Please enter number 1: 40
Please enter number 2: 50

Output

x
+
cmd
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