Exchange Values of Two Variables in C Using Function with Example

Introduction

In this tutorial, you’ll learn how to exchange the values of two variables in C using a function. This is done by using call by reference, which allows us to modify the original values of variables from within a function.


C Program to Exchange Values of Two Variables Using Function

#include <stdio.h>

void Exchange(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x, y;

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

printf("Enter value of y: ");
scanf("%d", &y);

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

Exchange(&x, &y);

printf("After Exchange: x = %d, y = %d\n", x, y);

return 0;
}

Explanation

  • The Exchange function takes two pointers as arguments.
  • It uses a temporary variable to swap the values of *a and *b.
  • In main(), we pass the addresses of x and y to the Exchange function.
  • This demonstrates call by reference, allowing us to modify the original variables.

Sample Output

Enter value of x: 5  
Enter value of y: 10
Before Exchange: x = 5, y = 10
After Exchange: x = 10, y = 5

Use Cases

  • Fundamental example of using pointers and call by reference in C.
  • Basis for more advanced topics like swapping values in sorting algorithms.
  • Important in interview questions and academic assignments.
Previous Article

Check if a Number is Prime in C – Function Program with Return Value

Next Article

Evaluate F(x) Using Recursion in C – Series Expansion with Factorial

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨