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>
2
3void swap(int*, int*);
4
5int main()
6{
7 int x, y;
8
9 printf("Enter the value of x and y\n");
10 scanf("%d%d",&x,&y);
11
12 printf("Before Swapping\nx = %d\ny = %d\n", x, y);
13
14 swap(&x, &y);
15
16 printf("After Swapping\nx = %d\ny = %d\n", x, y);
17
18 return 0;
19}
20
21void swap(int *a, int *b)
22{
23 int temp;
24
25 temp = *b;
26 *b = *a;
27 *a = temp;
28}
29
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
3void swap(int *,int *);
4int main()
5{
6
7 int n1,n2;
8 printf("\n\n Function : swap two numbers using function :\n");
9 printf("------------------------------------------------\n");
10 printf("Input 1st number : ");
11 scanf("%d",&n1);
12 printf("Input 2nd number : ");
13 scanf("%d",&n2);
14
15 printf("Before swapping: n1 = %d, n2 = %d ",n1,n2);
16 //pass the address of both variables to the function.
17 swap(&n1,&n2);
18
19 printf("\nAfter swapping: n1 = %d, n2 = %d \n\n",n1,n2);
20 return 0;
21}
22
23void swap(int *p,int *q)
24{
25 //p=&n1 so p store the address of n1, so *p store the value of n1
26 //q=&n2 so q store the address of n2, so *q store the value of n2
27
28 int tmp;
29 tmp = *p; // tmp store the value of n1
30 *p=*q; // *p store the value of *q that is value of n2
31 *q=tmp; // *q store the value of tmp that is the value of n1
32}
33
34
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