Problem 55

author
By Supreme2023-03-16
Problem Statement :
Write a C program to swap the two values using pointers.
Code:

#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;
}

Description :
  • This program demonstrates how to swap two values using pointers in C language.
  • The program starts by defining a function swap that takes two integer pointers as parameters.
  • The swap function uses a temporary variable temp to swap the values of the integers pointed to by a and b.
  • The main function declares two integer variables x and y and assigns them initial values of 6 and 9, respectively.
  • The main function then prints the values of x and y before the swap.
  • The main function calls the swap function, passing in the addresses of x and y as arguments.
  • The swap function swaps the values of x and y.
  • The main function prints the values of x and y after the swap.
  • Overall, this program swaps the values of x and y by passing their addresses to the swap function, which uses pointer manipulation to exchange their values.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.