Loops

advertisement
Loops
• Use a loop when you want some code to
repeat itself, until a certain condition is met
• 3 types of loops:
– While
– Do-While
– For
Counters
• A counter is a variable that is used to keep track of
the loop, and often determines when to end it
• A counter must be increased or decreased by a
certain amount each time through the loop (each
time = an “iteration”)
• Increasing a counter = “increment”
• Decreasing a counter = “decrement”
• Examples of incrementing / decrementing:
students = students + 1
health = health – 1
lives = lives + 5
(shortcut: students++)
(shortcut: health--)
(shortcut: lives+=5)
While Loops
• While loops are not guaranteed to execute at all; it
depends on whether the condition is met
• Syntax:
while (condition)
{
statements;
}
• Examples: WhileLoop1, WhileLoop2, WhileLoop3
• While loops are excellent for error checking
• Example: ErrorCheck
break
• If you want to cause a loop to stop executing
if some condition is met, put the word break
inside an if statement.
• If you use break, it MUST be the last code in
an if statement. If you break this rule, you
will get an “unreachable statement” error.
• Do not confuse “break” with “line break,”
which is when you move down to the next
line when displaying.
1. (Loops1) Using 3 different while loops…display every
number from 1 to 21, and then a line break. Next, display
every odd number from 7 to 29, then another line break.
Finally, display every # from 20 to 4, backwards.
2. (TheLetterQ) Ask the user to enter a word that begins with
Q or q. Error check with a while loop: If the word does not
begin with Q or q, insult the user and have them try again.
This should continue until they get it right. At the end, display
how many mistakes they made.
(example: “You entered 14 words that did not
begin with Q or q.”)
(more on next slide)
• 3. (Celery) Ask the user how many numbers
they want to enter. Then, using a while loop,
have the user enter those numbers. Finally,
display:
–
–
–
–
the total of those numbers
how many were odd
how many were even
how many were both greater than 70 and divisible
by 7.
Download