Chapter 4 Flashcards
(93 cards)
What is a loop in programming?
A program construct that repeatedly executes a set of statements while a condition is true
What is the loop body?
The statements executed repeatedly within a loop
What is an iteration?
One complete execution of the loop body
What real-world example illustrates looping?
Driving around the block until a baby falls asleep
What determines whether a loop continues or exits?
The loop expression’s evaluation (true = continue, false = exit)
What is a sentinel value?
A special input value that signals the end of data processing
What type of loop uses a sentinel value?
Loops that process input until a termination condition is met
What causes an infinite loop?
Forgetting to update a loop control variable or using the wrong loop expression
How do you prevent infinite loops?
Ensure loop variables are properly updated within the loop body
What is the basic structure of a while loop?
while expression is true, execute loop body, then recheck expression
What common task uses a loop to process lists?
Computing sums, averages, counts, or finding maximum/minimum values
In the baby asleep example, what represents the loop decision point?
Checking if the baby is awake
What happens when a loop’s expression evaluates to false?
Execution proceeds to the statement after the loop
When does a loop’s expression get evaluated?
Before each iteration of the loop body
What is a common mistake when writing loops?
Using the opposite expression than intended or forgetting input updates
What is a loop that never stops called?
An infinite loop
What is the purpose of initializing variables before a loop?
To ensure the loop body operates on correct starting values
What pattern allows processing unknown input amounts?
Using a sentinel value that marks the end of input
What is the output of this code with inputs 2, 4, 1, -1?
sum = 7 (sum adds inputs until -1 is encountered)
Why do we often use “val > -1” in loop expressions?
To exclude sentinel values like -1 from calculations
What happens if you forget to update the input within a loop?
The loop may become infinite or behave incorrectly
What does this loop accomplish: counting negative numbers?
It counts how many negative values are in a list
How can you find the maximum in a list using a loop?
Compare each input to current max and update if larger
What is wrong with initializing max to 0 for unknown lists?
If all list values are negative, max will be incorrect