Write a C program to swap two numbers using call by reference.
/* swap two numbers */
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a, b;
/* get two numbers from the user */
printf("Enter the value for a and b:");
scanf("%d%d", &a, &b);
printf("Before Swapping:\n");
printf("a: %d\tb: %d\n", a, b);
/* call by reference */
swap(&a, &b);
/* printing the results after swapping */
printf("After Swapping:\n");
printf("a: %d\tb: %d\n", a, b);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the value for a and b: 100 200
Before Swapping:
a: 100 b: 200
After Swapping:
a: 200 b: 100
Enter the value for a and b: 100 200
Before Swapping:
a: 100 b: 200
After Swapping:
a: 200 b: 100
No comments:
Post a Comment