Complementary task for topic: 6
M Nemeth 2023-08-29 15:21:04.626219'
Pointers: Pointer Swap
Pointers: Pointer Swap
Create a C program that swaps the values of two integer variables using pointers.
Before Swap:
a = 5
b = 10
After Swap:
a = 10
b = 5
Hint: Define two integer variables, a and b, and initialize them with some values.
Define two pointers, ptrA and ptrB, to point to the addresses of a and b, respectively.
Use pointers to swap the values of a and b without using a temporary variable.
Print the values of a and b before and after the swap.
Solution
#include
int main() {
int a = 5, b = 10;
int* ptrA = &a;
int* ptrB = &b;
printf("Before Swap:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
// Swap the values using pointers
*ptrA = *ptrA + *ptrB;
*ptrB = *ptrA - *ptrB;
*ptrA = *ptrA - *ptrB;
printf("\nAfter Swap:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
Explanation
In this task, we have two integer variables a and b with initial values of 5 and 10, respectively. We define two integer pointers ptrA and ptrB to store the addresses of a and b. We print the values of a and b before the swap using printf(). To swap the values of a and b, we use pointers. We first add the value pointed by ptrA to the value pointed by ptrB and store the result in the variable a. Then, we subtract the value pointed by ptrB from the new value of a and store the result in the variable b. Finally, we subtract the value pointed by ptrA from the new value of b and store the result in the variable a.