Module 6 - While-Loop Flashcards
What are the two types of loops?
Condition-controlled and count-controlled
Often we have to write code that performs
the same task multiple times. What are the disadvantages of duplicating code?
- It makes the program large
- Time-consuming
- May need to be correct in many places
What is the ‘while’ loop?
While condition is true, do task
What are the two parts of the while loop?
Test condition for true or false
If true, do the task and test again.
If false, exit structure.
What is the syntax for the while loop?
while condition:
____statements
What does a while loop look like in a flowchart?
Condition is in a diamond, if true, statements and go back to the start. If false, exit.
What is an iteration?
One execution of the body of the loop
Why is a ‘while’ loop considered a pretest loop?
- It won’t execute if condition is false to begin with
2. Requires some steps before the loop
What is an infinite loop?
While Loops have something in the code that eventually makes the condition FALSE, thereby stopping the loop.
Infinite loops don’t stop until program is interrupted
It occurs when programmer FORGETS to add that code
How do you avoid an infinite loop?
Make sure to change the while condition variable in the loop code
What are the two elements of a running total?
- A loop that reads each number in a series
2. An accumulator variable
What are 4 loop best practices?
- For variables that are changed inside the loop, initialize them BEFORE the loop
- Ensure while condition starts at TRUE
- Ensure while condition uses a variable that is CHANGED inside the loop
- Don’t place code in the loop unless it’s needed (e.g., printing the final result)
What are the augmented assignment operators (aka shorthand operators)?
\+= -= *= /= %=
for example, x = x+5 would be x += 5
What is a sentinel?
Special value that marks the end of a sequence of items
When the program reaches this value, it knows the end of the sequence was reached and the loop terminates
What are examples of sentinels?
Empty line, -1, empty string for input values, etc.
Sentinel value must be DISTINCT from other values so that you can’t confuse with it an actual value in the sequence