Title: C Control Structures Repetition Loops
1C Control Structures Repetition (Loops)
2Control Structurescontrolling the flow
3Remember
- Three-pronged approach
- General concepts
- C syntax
- Common applications/algorithms
4Repetition with Loops
- Selection has the program branching, deciding
which blocks of code to execute or skip, going
forward. - Repetition has the control point moving back to
execute the body of the loop again, while a
test condition is true. - Post-test do while(cond)Test at end,
body executes at least once! - Pre-test while(cond) Test at beginning,
may run zero times.
5General Form of Do-While Loop
do //always comment which loop //statements
to be repeated //called body of the
loop while(condition)
- Body executes at least once (blue arrow)
- Repeats, goes back, on true (green arrow)
- Exits loop on false (red arrow)
- Note closing semicolon.
6General Form of While Loop
while(condition) //statements to be
repeated //called body of the loop //always
comment which loop
- Body may not execute at all (test at beginning,
could be false first time). - ALWAYS repeats, goes back, at end of body (blue
arrow). - Re-enters body on true (green arrow)
- Exits loop, skipping body, on false (red arrow)
- Note NO closing semicolon.
7Run Again Loop
- Add to Temperature Conversion program to re-run
for multiple temps. - Use a character variable for yes/no answer (as
y or n) - Case issues? ltcctypegt and tolower()
- Code
8A Simple Run Again? Loopwith post-test do-while
9Input Validation
- Make temp conversion program smarter about bad
input for conversion choice (menu has only 1 or
2) - Can prevent (or deal with) bad input before using
it, instead of after the fact with an else. - Why a while loop instead of an if stmt?
10Input Validation w/ Error Msgusing pre-test
while loop
Basic Algorithm Get input While input is bad
Error message Get input again End of loop Rest
of program that Uses the input
11Advice on Writing Loops
- Properly indenting loop body aids finding errors.
- KEEP IT SIMPLE ! Only have the body of the loop
include code directly related to your purpose in
adding the loop in the first place. - An input validation loop would NOT include
calculations (other than those for the validity
test). - If you find yourself adding if statements or
other code trying to force the loop into
behaving the way you wish, consider changing it
from pre-test (while) to post-test (do-while) or
vice versa.
12Infinite Loops
- Common logic error stuck in loop
- Once a loop is entered, there must be SOMETHING
inside it that can change and make the loop test
go false for exit. - Often caused by forgetting to get a new input to
check.
13Loops and Accumulation
- Instructions are repeated, but same variables
(memory storage locations!) used entire time. - Trivial re-use new inputs/results overwrite old
ones - Something new make use of the old values
- Accumulate counts, sums, products
- May count all inputs in loop, or just some.
14Counting
- How do we count by hand?
- Count students in front row
15Counting by Hand vs C
- Need storage for the number a hand
- Need an int counter variable
- No fingers up before we start
- Initialize counter to zero (before loop- why?)
- Count by adding one to existing number raise
a finger - Increment counter inside loop
- Final count available after loop.
- CODE GPA averaging example
16Accumulation Operators
- Example accumulate a sum
- Normal sum sum result
- Shortcut sum result
- Meaning add result to current value of sum,
save (assign) back into same variable - Others
- - /
- Counting by 1 Increment shortcuts
- count same as count 1
- Also count-- decrement
17Lab 5 - Elevator
- Loading an elevator
- Instead of run again loop
- Loop watches total weight versus capacity
- Issues when getting out of the loop last rider
exceeds limit - Two versions do-while and while
- Second version handles situation better.
18Lab 5 Recap
- Apparently odd order of while loop elevator
solution - Unroll the loop
- First input before loop - common technique
- Problem with elevator run out of riders before
elevator is full?
19Sentinel Loop for Input Processing
Basic Algorithm Get first input While input is
not the sentinel value Use the current
input Get next input End of loop
- Sentinel Value
- Must be same data type as data input
- But not a valid real wordl value
20Lab 6 Height Converter
- Enter a height in inches, convert to feet and
inches - Example 73in becomes 6ft, 1 in
- Declare 3 int variables height, feet, inches
- Use integer division, modulus ()
- Print a message if tall (over 76in)
- Add a sentinel loop for multiple inputs
- use 0 as sentinal value be sure to tell user!
- Go back and count inputs and sum heights for
average calc at end (once, after loop).
21Common Loop Logic Errors
- Errors with vs. , and vs. or
- Infinite loop (never goes false once inside)
- Forget to ask for next input inside sentinel loop
- While loop never entered (never true at start)
- Counts or sums off
- Forgot to initialize to zero
- Increment or add at wrong point inside the loop
- General leaving things outside of loop that
should repeat. - TRY TO STICK WITH STANDARD FORMS IF POSSIBLE
DONT RE-INVENT THE WHEEL!!!