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
C Functions
C Function Arguments and Return Value
C Call by Value and Call by Reference
C Recursion
C Scope and Storage Classes
Exercises & Assignments
Write a C program to find the factorial of a number using recursion
Write a C program to swap two numbers using a function and pointers
Interview Questions & Answers
What is the difference between call by value and call by reference in C?
What is recursion in C?
What is the difference between local and global variables in C?
What are storage classes in C?
What is the use of the static keyword in C?