Problem 44

author
By Supreme2023-03-15
Problem Statement :
Write a function Exchange to interchange the values of two variables, say x and y. illustrate the use of this function in a calling function.
Code:

#include <stdio.h>

void exchange(int* x, int* y);

int main() {

//44. Write a function Exchange to interchange the values of two variables, say x and y.
//illustrate the use of this function in a calling function.

printf("\tExchange");
printf("\n====================================\n\n");

int x , y;

printf("Enter X : ");
scanf("%d",&x);

printf("\nEnter Y : ");
scanf("%d",&y);

printf("\n------------------------------------\n\n");
printf("Before Exchange: x = %d, y = %d\n", x, y);
exchange(&x, &y);
printf("\nAfter Exchange: x = %d, y = %d\n", x, y);
printf("\n------------------------------------\n\n");

return 0;
}

void exchange(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}

Description :
  • This program defines a function exchange that interchanges the values of two integer variables passed to it by reference. It also includes a main function that prompts the user to input two integer values, calls the exchange function, and outputs the new values of the two variables after the exchange.
  • The program includes the header file stdio.h, which provides input/output functions.
  • The function exchange is defined with two integer pointers x and y as parameters.
  • The main function is defined, which does the following: a. Prints a header message. b. Prompts the user to input two integers x and y. c. Prints the original values of x and y. d. Calls the exchange function, passing in the addresses of x and y. e. Prints the new values of x and y.
  • The exchange function swaps the values of x and y using a temporary variable temp.

Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.