Title: CPS 125: Digital Computation and Programming
1CPS 125 Digital Computation and Programming
- Repetition and Loop Statements
2Outline
- Using Loops to Solve Problems
- Counting Loop
- Conditional Loop
- Nested Control Structure
- Case Study Computing Radiation Level
- Debug and Test
- Common Programming Errors
3Using Loops to Solve Problems
- Problem 1 Mars Observer spacecrafts mission
plan called for seven orbit adjustment maneuvers
in order to move from initial orbit to the
desired orbit for mapping Mars. - Problem 2 Process a data file of Celsius
temperatures. Count how many are above 0ºC. - The number of temperatures 100
- Dont know the number, terminating on End
- Dont know the number, count till the end of file
4Using Loops to Solve Problems
- Three questions
- Any steps repeated?
- Know in advance how many times to repeat?
- If answer to second question is no, how long to
keep repeating the steps? - Solutions with loop statements
- A set of statements are executed multiple times
- Two basic types of repetition
- Counting loop
- Conditional loop
5Counting Loops
- A counter variable to control loops
- An initial value and an end value
- An increment amount
- Steps
- Set counter to an initial value
- Loop when (counter lt end value)
-
- increase counter by increment amount
6The while Statement
- Syntax
- while (loop repetition condition)
- statement
- Execution
- 1. Test loop repetition condition
- 2. If condition is true, execute statement and go
back to 1 - 3. If condition is false, exit while loop
- Executed 0 or more times
7Flowchart of while
8- count_mvr 0 / no maneuvers
done yet / - while (count_mvr lt 7) / test value of
count_mvr / - printf("Number of orbits to next maneuvergt
") - scanf("d", orbits)
- printf("Orbit period, in hours and
fraction of hoursgt ") - scanf("lf", period)
- time_to_mvr orbits period
- printf("Time to next maneuver is 6.1f
hours\n", time_to_mvr) - count_mvr count_mvr 1 /
increment count_mvr / -
- printf("All maneuvers complete\n")
Example Loop to process seven spacecraft
maneuvers
9- int count
- while (count lt 10)
- count count 1
- int count 0
- while (count lt 10)
- printf(d, count)
- Three critical steps initialization, testing,
and updating - Infinite loop
10Exercises of while
What is displayed if input is 10 scanf(d,
n) ev0 while (ev lt n) printf(3d\n,
ev) ev 2 printf(\n)
Predict the output i 0 while ( i lt 5 )
printf(3d3d\n, i, 10-i) i i 1
11Computing a Sum in a Loop
- double grade, total 0.0
- int count 0
- while (count lt 4)
- printf(Enter a grade -gt )
- scanf(lf, grade)
- total total grade
- count count 1
-
- printf(The total of the grades is lf, total)
12Computing a Product in a Loop
13Exercise
- printf (Enter an integergt)
- scanf(d, x)
- product x
- count 0
- while (count lt 4)
- printf(d\n, product)
- product x
- count
-
- Output values if a data value 5? 6? 7?
14Compound Assignment Operator
- Convert variable variable op expression
- to variable op expression
- op could be , -, , /, and
- ct ct 1 gt ct 1
- time time 1 gt time - 1
- product product data gt
- n n (x 1) gt
15Increment/Decrement Operators
- Increment operator
- Prefix 1. increment variable 2. evaluate
expression - Postfix 1. evaluate expression 2. increment
variable - e.g. i 2
- j i j i
- Decrement operator --
- Prefix and postfix
- e.g. n 4
- printf(3d, --n) printf(3d, n--)
- printf(3d, n) printf(3d, n)
- y i x i (if x 5 and i 2)
16Exercises
- r r / 10
- z z x 1
- q q r m
- m m (n p)
- i 3
- j 9
- n i --j
- m i j--
- p i j
int count 5 while (count--)
printf(count d\n, count)
int count 5 while (--count)
printf(count d\n, count)
17The for Statement
- Syntax
- for (initialization expression
- loop repetition condition
- update expression)
- statement
- Execution
- 1. Execute initialization expression
- 2. Test loop repetition condition
- 3. If it is true, statements are executed, update
expression is evaluated, go back to 2 - 4. If it is false, the for loop is exited
18for vs. while
- Logic of for is like that of while
Compare the code
int ctr for (ctr 1 ctr lt 10
ctr) printf(ctr d\n, ctr)
int ctr ctr 1 while (ctr lt 10)
printf(ctr d\n, ctr) ctr
19Exercise
- How many times does the body loop?
- for (count 0 count ltn count)
- sum count
-
- if execute the loop body n times, how to change
code? - How many times does the body loop?
- sum0 k1
- for (i -n i lt n-k i)
- sum ii
- for ( ) infinite loop
20Exercise
- Trace the loop for n8. Show the values of odd
and sum after the update of the loop counter for
each iteration? - sum0
- for (odd 1 odd lt n odd 2)
- sum odd
- printf(Sum of positive odd numbers less than d
is d.\n, n, sum)
21Exercise
- Trace the following program segment
- j10
- for (i1 ilt5 i)
- printf(d d \n, i, j)
- j -2
-
- Rewrite it so that it produced the same output
but uses 0 as the initial value of i ?
22Multiple Control Variables in for
expression 2
expression 3
expression 1
for ( i 1, k 1, j 1 i lt 10 j lt 3 k
i, j 2, k 2 i ) printf(i d, j
d, k d\n, i, j, k)
- initialize variables i, j, and k each to 1
- test to end loop when i gt 10 or j gt 3 k
- increment i by 1, j by 2, and k by 2 i
- print i, j, and k in the body of the loop
23The do-while Statement
- Syntax
- do
- statement
- while (loop repetition condition)
- Execution
- 1. Execute the statement
- 2. Test the repetition condition
- 3. If it is true, go back to 1
- 4. If it is false, exit the do-while loop
24Flowchart of do-while Loop
25while vs. do-while
int x 10, y 1 while ( x lt 10 ) if( x
10 ) y x x printf(x d\n,
x) printf(y d\n, y)
int x 10, y 1 do if( x 10 ) y
x x while ( x lt 10 ) printf(x d\n,
x) printf(y d\n, y)
26- How to generate number from 1 to 10 Using
different loops - for while
do-while -
- for (n1 nlt10 n) n1
n1 - while
(nlt10) do - ------
- ------ ------
------ - ------ ------
------ -
nn1 nn1 -
while (nlt10) -
27Conditional Loops
- The number of repetition is unknown before loop
execution begins - Looping continues until some event occurs or some
value is encountered - Steps
- Initialization
- Loop when condition is tested to be true
-
- update statement
28Example Using for Statement
- printf(Enter number of observed valuesgt )
- for (scanf(d, num_obs)
- num_obs lt 0
- scanf( d, num_obs))
- printf(Negative number invalid try againgt
) - Purpose of this code is to control the validity
of input data.
29Loop Design
- Condition Number of times loop must be executed
is unknown - Data too large to count
- Data depends on how computation proceeds
- Solution sentinel-controlled loops
- User enters a unique value to mark the end of
data - The program terminates when input value is equal
to the sentinel value
30Form of Sentinel-Controlled Loop
- 1. Get some data
- 2. While the sentinel value has not been
encountered - a. Process the data
- b. Get more data
- c. Go back to 2
31- / Compute the sum of a list of exam scores. /
- include ltstdio.hgt
- define SENTINEL -99
- int main()
-
- int sum 0, / sum of scores input so
far / - score / current score /
- printf("Enter first score (or d to quit)gt
", SENTINEL) - for (scanf("d", score)
- score ! SENTINEL
- scanf("d", score))
- sum score
- printf("Enter next score (d to
quit)gt ", SENTINEL) -
- printf("\nSum of exam scores is d\n",
sum) - return (0)
-
32- int sum 0, / sum of scores input so far /
- score / current score /
- while (score ! SENTINEL)
- printf("Enter the score (d to quit)gt ",
SENTINEL) - scanf("d", score)
- sum score
-
- Errors?
33 34End-of-File-Controlled Loops
- double grade 0.0, total 0.0
- printf(Enter a grade -gt )
- while (scanf(lf, grade) ! EOF)
- total grade
- printf(Enter a grade -gt )
-
- printf(The total of the grades is lf, total)
35EOF
- EOF character (end-of-file) a negative integer
- Z in DOS
- D in UNIX
- Operating system reads Z or D and converts to
EOF - In file operation functions, fscanf will return
EOF when it reads the end of the file
36Return Value of scanf
while(( vals scanf( lfclf, op1, action,
op2)) 3 )
scanf statement
result stored here optional
this value compared to
If the inputs are 35.6c9.3, 34.7bb, and Z, what
are output for vals scanf( lfclf, op1,
action, op2)
37Example Using fscanf
- / open the file /
- in_file fopen("scores.dat", "r")
- / begin reading from the file /
- for (input_status fscanf(in_file, "d",
score) - input_status ! EOF
- input_status fscanf(in_file, "d",
score)) - / process the value read from the file /
- printf("5d\n", score)
- sum score
-
- Input 7o instead of 70, what will happen?
38Correct Form for EOF loop
- input_status 1
- After loop,
- if (input_status EOF)
- printf(Sum of exam scores is d\n, sum)
- else
- fscanf(input, c, bad_char)
- printf( Error in input c \n,
bad_char) -
39Flag-Controlled Loop for Input Validation
- int id_number
- int error 0
- do
- printf("Please enter your identification
number -gt ") - scanf("d", id_number)
- if(id_number lt MINNO id_number gt MAXNO)
- printf("\nYour id number is
out-of-range\n") - error 1
-
- while (error)
40Nested Control Structure
- Create a 10x10 multiplication?
- for (row 1 row lt10 row)
- for (col1 collt 10 col)
- printf(4d, rowcol)
-
- printf(\n)
-
- Countdown from 10 to 0
- for (t 10 t gt0 t-- )
- for ( j 0 j lt t j )
- printf(2d\n, t)
41Exercise
- Which is better to implement a sentinel-controlled
loop? Why? - for (scanf(d, num) do
- num ! SENT scanf(d, num)
- scanf(d, num)) if (num ! SENT)
- /process num / /process num/
- while (num ! SENT)
42Case Study
- Problem In a certain lab, some yttrium-90 has
leaked into a coffee room. The leak would
currently expose 150 millirems of radiation a
day. The radiation level is only half of what it
was three days ago. The analysts want to know how
long it will be before the radiation is down to a
safe level of 0.466 millirem a day. They want a
chart to display radiation level for every three
days with the message unsafe and safe after every
line. It should stop just before the radiation
level is one-tenth of the safe level.
43Case Study
- Analysis - data requirements
- Constants (SAFE_RAD, SAFETY_FACT), Input
(init_radiation), Output (day, radiation_lev) - Design
- Initial algorithm
- 1. Initialize day to 0
- 2. Compute the stopping radiation level
- 3. Prompt user the enter the initial radiation
level - 4. Compute and display the day and radiation
level when radiation level exceeds stopping
level, indicating (un)safe
44Case Study
- Algorithm refinement
- Additional variable (min_radiation)
- Step 4 refinement
- 4.1 Initialize radiation_lev to init_radiation
- 4.2 while radiation_lev exceeds min_radiation
- 4.3 Display the value of day, radiation_lev,
and the string Unsafe or Safe - 4.4 Add 3 to the value of day
- 4.5 Compute radiation_lev for the next period
45Debug and Test
- Debugger program
- Single-step execution to trace
- Choose key variables to watch
- Set breakpoints to locate the error in a segment,
then to further trace the error - Trace unit coarse -gt fine
46Debug without Debugger
- Insert diagnostic printf to display critical
variables in critical points - define DEBUG 1 to turn on diagnostics and
define DEBUG 0 to turn off - Use
- fflush(stdout)
- to display every diagnostic message immediately
47Debug Example
- for (scanf("d", score)
- score ! SENTINEL
- scanf("d", score))
- sum score
- if (DEBUG)
- printf( score is d, sum is d\n,
score, sum) - fflush(stdout)
-
- printf("Enter next score (d to quit)gt ",
SENTINEL)
48Common Programming Errors
- for (scanf(dlf, code, amount),
- balance ! 0.0,
- scanf(dlf, code, amount)
-
-
- while (x gt xbig)
- x - 2
- xbig
49- printf(Experiment successful? (Y/N)gt )
- scanf( c, ans)
- if (ans Y)
- printf(Enter one number per line (d to
quit)\ngt , SENT) - scanf(d, data)
- while (data ! SENT)
- sum data
- printf(gt )
- scanf(d, data)
- else
- printf(Try it again tomorrow.\n)
- printf(Now follow correct shutdown
procedure.\n)
50- scanf(dlf, code, amount)
- while (balance ! 0.0)
-
- scanf(dlf, code, amount)
-
- do
- printf(One more time? (1 continue/0 quit)gt )
- scanf(d, again)
- while (again 1)
51break and continue statement
- break statement
- Used in loops (e.g., for, while, and do-while
statements) and in the switch statement - Causes immediate exit from innermost loop (exits
switch in switch statement) - continue statement
- Used in loops only (e.g., for, while, and
do-while, NOT in the switch statement Why?) - Causes immediate exit from BODY of innermost loop
AND loop condition is reevaluated for loop
continuation
52break Statement
while ( expr1 ) statement1 while ( expr2 )
statement2 statement3 if ( expr3
) break statement4 statement5
when expr3 is true break exits loop
and the next stmt is done
even if expr2 is still true!
53continue Statement
while ( expr1 ) statement1 while ( expr2 )
statement2 statement3 if ( expr3
) continue statement4 statement5
when expr3 is true continue exits loop BODY
and goes BACK to see if expr2 is still true!
54continue Statement
do statement1 do statement2 statement3 if
( expr3 ) continue statement4 while (expr2
) statement5 while (expr1 )
when expr3 is true continue exits loop BODY
and tests to see if expr2 is still true! If it
is, control continues in the loop
55continue Statement
Does same thing in a for() statement
for ( expr1 expr2 expr3 ) statement1 state
ment2 if( expr4 ) continue statement3
jumps to end of loop
which causes expr3 to be executed and expr2 to
be evaluated for continuing the loop
56- int ctr 0
- while (ctr lt 6)
- if (ctr lt 3)
- ctr 2
- printf(d\n, ctr)
- continue
-
- else
- printf(d\n, ctr)
- break
-
- printf(Bottom of loop\n)
-
- What is printed?