Complementary task for topic: 6
M Nemeth · 2023-08-29 15:21:04.626219'
Pointers: Pointer Swap with Function
Pointers: Pointer Swap with Function
Create a C program that swaps the values of two variables using pointers and a separate swap function.
Expected output:
Before Swap:
a = 5
b = 10
After Swap:
a = 10
b = 5
Hint: Define a function swap that takes two integer pointers as arguments and swaps the values of the variables pointed to by the pointers.
Define two integer variables, a and b, and initialize them with some values.
Call the swap function with the addresses of a and b to swap their values.
Print the values of a and b before and after the swap.
Solution
#include
void swap(int* ptrA, int* ptrB) {
int temp = *ptrA;
*ptrA = *ptrB;
*ptrB = temp;
}
int main() {
int a = 5, b = 10;
printf("Before Swap:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
swap(&a, &b);
printf("\nAfter Swap:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
Explanation
In this task, we define a swap function that takes two integer pointers ptrA and ptrB as arguments. Inside the swap function, we use a temporary variable temp to store the value pointed to by ptrA. We then assign the value pointed to by ptrB to ptrA. Finally, we assign the value stored in temp to ptrB, effectively swapping the values of the variables. In the main function, we have two integer variables a and b with initial values of 5 and 10, respectively. We print the values of a and b before the swap using printf(). We call the swap function with the addresses of a and b using the & operator. After the swap, we print the values of a and b again, showing that their values have been swapped.