Write a C program to swap two numbers using pointers and functions. How to swap two numbers using call by reference method. Logic to swap two number using pointers in C program.
Example
Input
Input num1: 10 Input num2: 20
Output
Values after swapping: Num1 = 20 Num2 = 10
Required knowledge
Basic C programming, Functions, Pointers
Must know – Program to swap two numbers using bitwise operator
Logic to swap two numbers using call by reference
Swapping two numbers is simple and a fundamental thing. You need not to know any rocket science for swapping two numbers. Simple swapping can be achieved in three steps –
- Copy the value of first number say num1 to some temporary variable say temp.
- Copy the value of second number say num2 to the first number. Which is num1 = num2.
- Copy back the value of first number stored in temp to second number. Which is num2 = temp.
Let us implement this logic using call by reference concept in functions.
Program to swap two numbers using call by reference
Before moving on to other post, learn more ways to play with swapping numbers.
Read more – Program to swap first and last digits of a number
Output
Enter two numbers: 10 20 Before swapping in main Value of num1 = 10 Value of num2 = 20 After swapping in swap function Value of num1 = 20 Value of num2 = 10 After swapping in main Value of num1 = 20 Value of num2 = 10
Happy coding