#include <stdio.h>
void swap(int *a, int *b);
int main() {
//55. Write a C program to swap the two values using pointers.
printf("\tSwapping\n");
printf("============================\n\n");
int x = 6, y = 9;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("\nAfter swap: x = %d, y = %d\n", x, y);
return 0;
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
swap
that takes two integer pointers as parameters.swap
function uses a temporary variable temp
to swap the values of the integers pointed to by a
and b
.main
function declares two integer variables x
and y
and assigns them initial values of 6 and 9, respectively.main
function then prints the values of x
and y
before the swap.main
function calls the swap
function, passing in the addresses of x
and y
as arguments.swap
function swaps the values of x
and y
.main
function prints the values of x
and y
after the swap.x
and y
by passing their addresses to the swap
function, which uses pointer manipulation to exchange their values.