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.
Table of Contents
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.
#include <stdio.h>
void swap(int *ptr1, int *ptr2)
{
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
void main()
{
int num1, num2;
printf("Enter the first number ");
scanf("%d", &num1);
printf("Enter the second number ");
scanf("%d", &num2);
printf("Before swapping num1 = %d and num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After swapping num1 = %d and num2 = %d", num1, num2);
}
Output
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
4 thoughts on “C Program to Swap two numbers using Pointers”