The problem statement here is to swap given two numbers by making use of pointers in C. Pointer variables in C stores the address value (actual memory location) of another variable. We are going to declare two int pointers and then assign them the addresses of two int variables. In order to swap the two variables we just need to swap their address values.
C program to swap two numbers using pointers - Source code
int main()
{
int x,y,temp,*a,*b;
printf("Enter the two numbers:\n");
scanf("%d%d",&x,&y);
printf("Before swapping:\n x = %d\n y = %d\n",x,y);
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After swapping:\n x = %d\n y = %d\n",x,y);
return 0;
}
Program Output
Case 1:
Enter the two numbers:
30
56
Before swapping:
x = 30
y = 56
After swapping:
x = 56
y = 30
Case 2 :
Enter the two numbers:
1
0
Before swapping:
x = 1
y = 0
After swapping:
x = 0
y = 1
Program Explanation
1. In the declaration part of the program, three integer variables x,y and temp are declared alongside with two integer pointer variables a and b.
2. After accepting two integers from the user using the scanf function, values of x and y are printed(before swapping).
3. Pointer a is assigned the address value of the variable x using the & operator. Similarly, the memory address of variable y is assigned to pointer b.
4. In the next statement, value of pointer b is stored in the temp variable using assignment operator. Now, we can assign the value of pointer a to b and value of pointer b (stored in variable temp) to a.
5. By swapping the memory addresses of the variables, their values automatically get swapped.
C program to swap two numbers using pointers - Source code
Program Output
Program Explanation
1. In the declaration part of the program, three integer variables x,y and temp are declared alongside with two integer pointer variables a and b.
2. After accepting two integers from the user using the scanf function, values of x and y are printed(before swapping).
3. Pointer a is assigned the address value of the variable x using the & operator. Similarly, the memory address of variable y is assigned to pointer b.
4. In the next statement, value of pointer b is stored in the temp variable using assignment operator. Now, we can assign the value of pointer a to b and value of pointer b (stored in variable temp) to a.
5. By swapping the memory addresses of the variables, their values automatically get swapped.
need an explanation for this answer? contact us directly to get an explanation for this answer