Exercise 5.2 pp. 122-123.
To run a C++ program:
myprogram.cpp
)cd
command to get to the folder where your C++ files areg++ myprogram.cpp
to compile. If there are error messages, correct the mistake and compile again (note: an old executable a.out
will still be there until it is overwritten by a new one. If your program failed to compile and you still try to run it, you would be running the old version).a.out
on the command line. If you get file not found
error, use ./a.out
instead.
Write a void C++ function order
that takes two pointers
to int
, checks if the value at the first address is larger
than at the second one, and if it is, switches the values at the two
addresses. I.e. if I have n = 7, m = 2
then after the call
order(&n,&m)
n should have the value 2, and m the
value 7.
Submit the file with your function and the testing code. Your program must compile and run on the dungeon machines. Important: Even if you are familiar with a different C++ style of declaring parameter passing by reference, please use the style that was used in the example in class.
Consider the following two C++ loops, where n and m are integer (int) variables and p and q are pointers to ints.
while(n >= m) {
n = n - 1;
}
while (*p >= *q) {
*p = *p - 1;
}
For each of the loop please answer: is it guaranteed to terminate? If yes, please explain why. If not, please write a program that initializes variables used in the loop in such a way that the program goes into an infinite loop (Ctrl-C stops a program).
Extra credit (added 2/23): are there additional possiblities of divergence if the type of the variables is not restricted to ints?