1#include <stdio.h>
2int main() {
3 double a, b;
4 printf("Enter a: ");
5 scanf("%lf", &a);
6 printf("Enter b: ");
7 scanf("%lf", &b);
8
9 // Swapping
10
11 // a = (initial_a - initial_b)
12 a = a - b;
13
14 // b = (initial_a - initial_b) + initial_b = initial_a
15 b = a + b;
16
17 // a = initial_a - (initial_a - initial_b) = initial_b
18 a = b - a;
19
20 printf("After swapping, a = %.2lf\n", a);
21 printf("After swapping, b = %.2lf", b);
22 return 0;
23}
24
1#include <stdio.h>
2int main()
3{
4 int a, b, temp;
5 printf("enter the values of a and b: \n");
6 scanf("%d%d", &a, &b );
7 printf("current values are:\n a=%d\n b=%d\n", a, b);
8 temp=a;
9 a=b;
10 b=temp;
11 printf("After swapping:\n a=%d\n b=%d\n", a, b);
12}
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 a = 10;
6 int b = 5;
7
8 //swap start
9 a = a + b; //a = 10 + 5 = 15
10 b = a - b; //b = 15 - 5 = 5
11 a = a - b; //a = 15 - 5 = 10
12
13 printf("a = %d / b = %d\n", a, b);
14 //a = 5 / b = 10
15 return 0;
16}
17
18
19/*You can create a function*/
20
21void swap(int *a, int *b)
22{
23 *a = *a + *b; //a = 10 + 5 = 15
24 *b = *a - *b; //b = 15 - 5 = 5
25 *a = *a - *b; //a = 15 - 5 = 10
26}
27
28int main()
29{
30 int a = 10;
31 int b = 5;
32
33 //call with adress of the var
34 swap(&a, &b);
35 printf("a = %d / b = %d\n", a, b);
36 //a = 5 / b = 10
37 return 0;
38}