Here is the code for swapping two numbers using a function which is based on pointers. The basic concept used is pass by reference.
void swap(int *x, int *y)
{
int tmp;
tmp = *y;
*y = *x;
*x = tmp;
}
int main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
printf("\nBefore swapping: a = %d and b = %d\n", a, b);
swap(&a, &b);
printf("After swapping: a = %d and b = %d\n", a, b);
return 0;
}
Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
Code
#include <stdio.h>void swap(int *x, int *y)
{
int tmp;
tmp = *y;
*y = *x;
*x = tmp;
}
int main()
{
int a, b;
printf("Enter two numbers: ");
scanf("%d%d", &a, &b);
printf("\nBefore swapping: a = %d and b = %d\n", a, b);
swap(&a, &b);
printf("After swapping: a = %d and b = %d\n", a, b);
return 0;
}
Output
Enter two numbers: 10 20Before swapping: a = 10 and b = 20
After swapping: a = 20 and b = 10
No comments:
Post a Comment