Q and A for Chapter 7. Students of CS104, and me, your benevolent professor, Victor T. Norman, PhD. Multiple Assignment. Q: How would using multiple assignment be helpful? If you want to store two different numbers, why not just use two different variables?
Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.
Q and A for Chapter 7
Students of CS104, and me, your benevolent professor, Victor T. Norman, PhD
Q: How would using multiple assignment be helpful? If you want to store two different numbers, why not just use two different variables?
A: Consider swapping two values, where i and j were assigned values previously. Then to swap:
itemp = i
i = j
j = itemp
Q: Please explain the updating variables: if you update it, then is the original value gone forever then?
A: Yes, the original value is gone. You can tell this by drawing the picture of what
x = x + 1 does.
Note: if you use x = x + 1 or x += 1, you have to declare x and initialize it to a value beforehand.
E.g., you have to write x = 0 beforehand.
Q: Is there an augmented assignment like -= to decrement a value?
A: Yes! There is also *= , /= , **= , %= , etc., etc. Lots of them.
If you see
var = var<op> <value>
you can convert to
Q: (Prof’s question) Suppose you have a while loop like this:
while var1 <op> var2:
Is it good/bad/ugly to alter the value of var1 or var2 in the body of the loop?
A: You almost *always* alter the value of var1 or var2 in the body, or you would have an infinite loop.
Q: (Prof’s question) Is the body of a while loop always executed?
A: No: if the boolean expression is False the first time, the body is not run at all.
Q: How often is the body of a while loop executed?
A: Until the boolean expression is False.
Q: Are there interesting applications of infinite loop? Are infinite loops ever used?
A: Infinite loops are used a lot, actually. Your beloved cellphone does this, basically:
wait for event (button pushed, etc.)
figure out what user wants to do
do what user asked.
Q: Could we go over what a break is a little more? When and how to use this? Why would you want to get out of the loop? Can it make a loop skip a portion of code?
A: break can be very useful. As the book says, you can use it to test when to get out of a while loop in the middle of the body.
(Let’s rewrite the loop in 7.4 without the break.)
Q: The idea of making algorithms is still vague to me. Can you give more examples?
A: Algorithm for cleaning a whiteboard.
Algorithm for cutting a pan of brownies into equal-sized pieces.
Algorithm for deciding how to dry yourself when you get out of the shower.
Algorithm for making a scribbler find its way out of a maze…