C Program to Swap two numbers using Pointers

Swapping the values of two variables is a common task in programming. In C pointers provide an option to indirectly manipulate variables’ values, Enabling us to swap the values of two variables by using pointers. In this article, we are going to write a C program to swap two numbers using pointers.

C Program to Swap two numbers using Pointers

Pointers in C

Pointers in C are variables that hold the memory address of another variable. Pointers provide an option to access and modify values stored at those addresses indirectly.

Swapping two numbers using Pointers

Two swaps two numbers using a pointer, we need a temporary pointer variable to temporarily store the value pointed by one variable during the swap operation.

Output

C Program to Swap two numbers using Pointers

How the above C Program Works

  • The program starts with declaring two variables num1 and num2 of type int.
  • The program asks the user to input two numbers.
  • Before swapping the values current values of num1 and num2 are printed.
  • The swap function takes two pointer arguments (ptr1 and ptr2) that point to num1 and num2.
  • It uses a temporary variable temp to swap the values indirectly by using pointer.
  • After swapping updated values of num1 and num2 are printed.

Happy Coding

See Also

4 thoughts on “C Program to Swap two numbers using Pointers”

Leave a Comment