write a c program to swap the content of 2 variables entered through the command line using function and pointer.
Write a C program to swap the content of two variables entered through the command line using function and pointer
Answer:
To write a C program that swaps the contents of two variables entered through the command line using a function and pointers, follow these steps:
-
Include Necessary Headers:
- The program will require the use of the standard input-output library and assertions for simple debugging.
-
Function Definition to Swap Two Variables:
- Use a function
swap
that takes two pointers as arguments and swaps the values they point to.
- Use a function
-
Command-Line Argument Handling:
- Parse the command-line arguments to retrieve the two numbers.
-
Invoke the Swap Function:
- Call the
swap
function, passing the addresses of the variables.
- Call the
Here’s the complete code:
#include <stdio.h>
#include <stdlib.h>
// Function to swap two integer variables using pointers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(int argc, char *argv[]) {
// Ensure there are exactly two additional command-line arguments
if (argc != 3) {
printf("Usage: %s <number1> <number2>\n", argv[0]);
return 1;
}
// Convert command-line arguments to integers
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
// Print original values
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
// Call the swap function with pointers to num1 and num2
swap(&num1, &num2);
// Print swapped values
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
Explanation:
-
Including Necessary Headers:
- We include
<stdio.h>
for input/output functions and<stdlib.h>
for theatoi
function that converts strings to integers.
- We include
-
Function Definition (
swap
):- The
swap
function takes two pointers to integers (int *a
,int *b
). It uses a temporary variabletemp
to swap the values of the variables pointed to bya
andb
.
- The
-
Command-Line Argument Handling:
- The
main
function checks if the correct number of command-line arguments are provided (argc != 3
checks for exactly 2 additional arguments). If not, it prints a usage message and exits. - If arguments are correct, it converts them from strings to integers using
atoi
.
- The
-
Invoke the Swap Function:
- The original values of
num1
andnum2
are printed. - The
swap
function is called with the addresses ofnum1
andnum2
(&num1
,&num2
). - Finally, the swapped values are printed.
- The original values of
How to Run the Program:
- Save the program to a file named, for example,
swap.c
. - Compile the program using a C compiler (e.g.,
gcc
):gcc -o swap swap.c
- Run the program with two numbers as arguments:
./swap 5 10
Final Answer:
This swap.c
program reads two integers from the command line, swaps their values using a function that takes pointers, and then prints the swapped values. This demonstrates the use of pointers and functions in C for variable manipulation.