1// Method 1: With temporary variable
2temp = A
3A = B
4B = temp
5// without temporary variable
6// Method 2: Addition and subtraction
7A = A + B
8B = A - B
9A = A - B
10// Method 3: Muitply and Divide
11A = A * B
12B = A / B
13A = A / B
1
2#include<stdio.h>
3 int main()
4{
5int a=10, b=20;
6printf("Before swap a=%d b=%d",a,b);
7a=a+b;//a=30 (10+20)
8b=a-b;//b=10 (30-20)
9a=a-b;//a=20 (30-10)
10printf("\nAfter swap a=%d b=%d",a,b);
11return 0;
12}
13
1#include <stdio.h>
2#include <stdlib.h>
3
4int main()
5{
6 //initialize variables
7 int num1 = 10;
8 int num2 = 9;
9 int tmp;
10
11 //create the variables needed to store the address of the variables
12 //that we want to swap values
13 int *p_num1 = &num1;
14 int *p_num2 = &num2;
15
16 //print what the values are before the swap
17 printf("num1: %i\n", num1);
18 printf("num2: %i\n", num2);
19
20 //store one of the variables in tmp so we can access it later
21 //gives the value we stored in another variable the new value
22 //give the other variable the value of tmp
23 tmp = num1;
24 *p_num1 = num2;
25 *p_num2 = tmp;
26
27 //print the values after swap has occured
28 printf("num1: %i\n", num1);
29 printf("num2: %i\n", num2);
30
31 return 0;
32}
33
1#include<stdio.h>
2
3int main()
4{
5 int x = 20, y = 30, temp;
6
7 temp = x;
8 x = y;
9 y = temp;
10
11 printf("X = %d and Y = %d", x, y);
12
13 return 0;
14}