Homework 5 Solution Guidelines
1. As mentioned in posts on the messageboard, with the restrictions placed in the
question, there is no option but to do an “in-place rotation” for this question. For
example, the following code:
b += a;
a = b - a;
b -= a;
results in swapping the values of a and b, without using any other memory.
This can easily be generalized to four variables a, b, c, d. One simple way is to add
a to b, then obtain b’s old value by subtraction (as above) and add to c, then do the same
for d. Now you have the four variables storing the values a, a+b, b+c, c+d. Now
you can overwrite a by the old value of b (which can be obtained by subtraction), etc.
Using pointers changes nothing as long as you use the correct syntax to reference and de-
reference. Keeping an extra pointer to the “first” variable a can help make the code a
little easier, hence the provision in the question. You can do without it.
There were a couple of popular ways to go wrong on this one. If you used malloc() to
get a new integer variable, this is a correct solution except that it violates the restriction in
the question. This will get you nearly full credit. Defining a pointer and then using that
variable to store the value of an int sidesteps the question, is bad and unportable code,
and violates a restriction – this is part credit. Defining a pointer, and then de-referencing
that (dangling) pointer without allocating any memory is bad and risky code, and is also
little or no credit.
One issue that not many people raised is the issue of overflow – an int may not be able
to hold the sum of two int s. The solution is to use bit operations, which we have not
yet covered. For this homework, there is no deduction for failing to check for variable
overflow.
2. As below. Note that in a case such as this it is not sufficient to type in the code and use
printf statements to observe the values of the variables at various points in the code. (The
rest of this comment was also posted on the messageboard prior to due date.) We have
said many times that part of the risks in C is that operations that are not logically correct
are nevertheless perfectly legal, and will compile. Sometimes they will generate
warnings, other times not even that.
So the programmer must actually understand programming. It is not enough to write code
that one is reasonably but not completely sure is correct, then run it and assume it is
correct if “it works”. It may not work another time, or on another compiler or platform.