3. (24 pts) Consider a subroutine swap that takes two parameters and simply swap
ID: 3714910 • Letter: 3
Question
3. (24 pts) Consider a subroutine swap that takes two parameters and simply swaps their values. For example, after calling swap (X, Y), X should have the original value of Y and Y the original value of X. Assume that variables to be swapped can be simple or subscripted (elements of an array), and they have the same type (integer). Show that it is impossible to write such a general-purpose swaps ubroutin e in a language with: (a) (12 pts) parameter passing by value. (b) (12 pts) parameter passing by name. Hint: for the case of passing by name, consider mutually dependent parameters.Explanation / Answer
#include <stdio.h>
main(void) {
int a = 10, b = 20, x = 30, y = 40, p = 50, q = 60;
printf("Before swap using pass by reference a is %d and b is %d ", a, b);//Prints 10,20
printf("Before swap using pass by value x is %d and y is %d ", x, y);//Prints 30,40
printf("Before swap using pass by value p is %d and q is %d ", p, q);//Prints 50,60
swap(&a, &b);//calls call by reference function
swapnum(x,y);//calls call by value function
printf("After swap using pass by reference a is %d and b is %d ", a, b);//Prints 20,10
printf("After swap using pass by value x is %d and y is %d ", x, y);//Prints 30,40 as swap is limited to function itself
printf(" ");
swapnumprint(p,q);//calls call by value function
}
void swap(int* X, int* Y) {
int temp = *X;
*X = *Y;
*Y = temp;
}
void swapnum(int X, int Y) {
int temp = X;
X = Y;
Y = temp;
}
void swapnumprint(int X, int Y) {
int temp = X;
X = Y;
Y = temp;
printf("After swap using pass by value printed inside the function is %d and %d",X,Y);//Swap happened inside the function
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.