Write a C program to swap two numbers using a function and pointers

Description: Write a function which swaps the values of two variables. The values must change in the main() function.

Hint:

  • Pass the addresses of the variables with &, and use * inside the function.

C program to swap two numbers using pointers

#include <stdio.h>

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

int main(void) {
    int x, y;

    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);

    swap(&x, &y);
    printf("After swapping: x = %d, y = %d\n", x, y);
    return 0;
}

Output:

Output of the above program is

Enter two numbers: 5 9
After swapping: x = 9, y = 5

How it works

  • The function gets the addresses of x and y, so it changes the original values.
  • With normal parameters (call by value), the function would swap only its own copies.

Read Call by Value and Reference.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.