Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote