Write a C program to swap two numbers using pointers.
#include <stdio.h>
/* swaps the given two numbers using pointers */
void swap(int *x1, int *x2) {
int temp;
temp = *x1;
*x1 = *x2;
*x2 = temp;
return;
}
int main() {
int v1, v2;
/* get the first input from the user */
printf("Enter your first input:");
scanf("%d", &v1);
/* get the second input from the user */
printf("Enter your second input:");
scanf("%d", &v2);
/* data befor swapping */
printf("Before Swapping:\n");
printf("Value1: %d\tValue2: %d\n", v1, v2);
/* swaps given two numbers */
swap(&v1, &v2);
/* result after swapping */
printf("After Swapping:\n");
printf("Value1: %d\tValue2: %d\n", v1, v2);
return 0;
}
/* swaps the given two numbers using pointers */
void swap(int *x1, int *x2) {
int temp;
temp = *x1;
*x1 = *x2;
*x2 = temp;
return;
}
int main() {
int v1, v2;
/* get the first input from the user */
printf("Enter your first input:");
scanf("%d", &v1);
/* get the second input from the user */
printf("Enter your second input:");
scanf("%d", &v2);
/* data befor swapping */
printf("Before Swapping:\n");
printf("Value1: %d\tValue2: %d\n", v1, v2);
/* swaps given two numbers */
swap(&v1, &v2);
/* result after swapping */
printf("After Swapping:\n");
printf("Value1: %d\tValue2: %d\n", v1, v2);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input:10
Enter your second input:20
Before Swapping:
Value1: 10 Value2: 20
After Swapping:
Value1: 20 Value2: 10
Enter your first input:10
Enter your second input:20
Before Swapping:
Value1: 10 Value2: 20
After Swapping:
Value1: 20 Value2: 10
this link might be help you C program to swap two numbers
ReplyDeletehttp://programmergallery.com/c-program/c-program-swap-two-numbers.php