1. Design a swap module that accepts two arguments of the Real data type and swa
ID: 3555622 • Letter: 1
Question
1. Design a swap module that accepts two arguments of the Real data type and swaps them.
2. Validate understanding This was previous answer
PROGRAM: Swap_module
Input: two numbers
Step 1. INPUT number in variable argument[1]
Step 2. INPUT number in variable argument[2]
Step 3. Callswap(arugment[1],argument[2])
Step 4. Exit Program
This is my Code: is this correct
// the swap module accepts two integer arguments and swap the values.
Module swap (Integer Ref a, Integer Ref b)
Declare Integer a;
Declare Integer b;
Declare Integer temp;
Set temp = a;
Set a = b;
Set b = temp;
End Module
Explanation / Answer
Your pseduo code seems correct to me but it uses extra memory to swap i.e it uses extra temp variable to swap which is not necessary. You can swap two variables without actually using extra memory in form of temp variable.
Module swap (Integer Ref a, Integer Ref b)
Declare Integer a;
Declare Integer b;
Declare Integer temp;
Set a = a + b;
Set b = a - b;
Set a = a - b;
End Module
Above pseudo code uses addition to swap two variables but you can also use xor operation or multiplication. You can view java code for the same here(http://opensourceforgeeks.blogspot.in/2013/12/swapping-two-numbers-without-using.html).
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.