Swapping two numbers using pointers in C is a common exercise that helps illustrate the use of pointers for manipulating variables. In this program, we will define a function that takes two pointers as parameters and swaps the values they point to.
Program: Swap Two Numbers Using Pointers
Here’s a simple C program that demonstrates how to swap two numbers using pointers:
Explanation of the Program
Header Files:
#include <stdio.h>
: This is included for input and output functions likeprintf
andscanf
.
Function Declaration:
void swap(int *a, int *b)
: This function takes two integer pointers as parameters. Thevoid
return type indicates that this function does not return a value.
Swapping Logic:
- Inside the
swap
function:- A temporary integer variable
temp
is declared. - The value pointed to by
a
is stored intemp
. - The value pointed to by
b
is assigned to the location pointed to bya
. - Finally, the value in
temp
(originally froma
) is assigned to the location pointed to byb
. This effectively swaps the values of the two integers.
- A temporary integer variable
- Inside the
Main Function:
- Two integer variables
num1
andnum2
are declared to hold the user input. - The program prompts the user to enter two numbers and stores them in
num1
andnum2
usingscanf
. The&
operator is used to get the addresses of these variables. - Before calling the
swap
function, the program prints the values ofnum1
andnum2
. - The
swap
function is called with the addresses ofnum1
andnum2
as arguments. - After the swap operation, the new values of
num1
andnum2
are printed.
- Two integer variables
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Example Output
When you run the program, the output will be similar to:
Conclusion
The program demonstrates how to swap two numbers using pointers in C. By passing the addresses of the variables to the swap
function, we can modify the original variables directly. This exercise highlights the power of pointers for manipulating data in C, enabling more efficient and flexible code.