Swapping Programs in C

Swapping in C is one of the easiest programs that every beginner programmer should need to know. So here are the three different types of programs for the swapping.

Swap two variable with the third variable by procedural approach:

Source Code:

// c program to swap two variables using third variable
#include <stdio.h>

int main() {
// declaring variables used in program
int num1,num2,temp;

// assinging values to variables 
num1 = 12;
num2 = 13;

// displaying the before swapping output
printf("***Before swapping***");
printf("\nnum1 = %d",num1);
printf("\nnum2 = %d",num2);

// swapping operation using temp variable
temp = num1;
num1 = num2;
num2 = temp;

// displaying the after swapping output
printf("\n\n***After swapping***");
printf("\nnum1 = %d",num1);
printf("\nnum2 = %d",num2);

return 0;
}

Output:

***Before swapping***
num1 = 12
num2 = 13

***After swapping***
num1 = 13
num2 = 12

Swap two variable without using the third variable by procedural approach:

Source Code:

// c program to swap two variables without using third variable
#include <stdio.h>

int main() {
// declaring variables used in program
int num1,num2;

// assinging values to variables 
num1 = 12;
num2 = 13;

// displaying the before swapping output
printf("***Before swapping***");
printf("\nnum1 = %d",num1);
printf("\nnum2 = %d",num2);

// swapping operation 
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;

// displaying the after swapping output
printf("\n\n***After swapping***");
printf("\nnum1 = %d",num1);
printf("\nnum2 = %d",num2);

return 0;
}

Output:

***Before swapping***
num1 = 12
num2 = 13

***After swapping***
num1 = 13
num2 = 12

Recommended Post