Title: Repetition in the programs
1Repetition in the programs
- Example 1 Suppose we want to display the
consecutive digits 0,1,2,.9. For doing that
adding one to the previous number should be
repeated 10 times. - Example 2 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. The spacecraft
would have needed to execute similar sets of
instructions seven times, one set for each
maneuver.
2Repetition in the programs
- The questions that determined whether loops
are required in the algorithm - Are there any repeated steps in the algorithm?
- If repetition is required, how many times these
steps should be repeated? - If the number of repetition is unknown, how long
the repeating the steps should be kept? - The answer to question 1 indicates whether
algorithm needs loop or not, and the answers to
questions 2 and 3 determine which loop structure
need to be used
3Counting loop (counter-controlled loop)
- The repetition is managed by a loop control
variable whose value represents a count - Set loop control variable to an initial value (0)
- while loop control variable lt final value
-
- increase loop control variable by increment
value (1)
4- / Loop to Process Seven Spacecraft Maneuvers /
- 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")
5count_mvr 0
Flowchart of While statement
count_mvr lt7
true
false
.. increase count_mvr
by 1
Exit loop
6Counting loop and while statement
- Syntax of while statement
- while (loop repetition condition)
- statement
- Three steps for a loop with a control variable
are - Initialization of loop control variable (if
missing loop may repeat 0 or a wrong number of
times) - Testing loop control variable (loop will be
executed zero times if the condition is initially
false) - Updating loop control variable (if missing the
loop will execute forever, which is referred to
as infinite loop)
7Computing a Sum in the Loop
- printf("Enter number of maneuversgt ")
- scanf("d", num_mvrs)
- total_time 0.0
- count_mvr 0
- while (count_mvr lt num_mvrs) loop
can be repeated for any number - 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\n", - time_to_mvr)
- count_mvr count_mvr 1
- total_time total_time time_to_mvr
accumulator increases with -
each loop iteration
-
- printf("All maneuvers complete\n")
- printf("Total time spent in maneuver phase
is 6.1f hours\n", - total_time) printing
the value of accumulator
accumulator variable
8Computing a Product in a Loop
- The loop control variable holds the result of the
computation that is performed in the loop - product 1
- while (product lt 10000)
- printf(d\n, product) / Display
product so far / - printf(Enter next itemgt )
- scanf(d, item)
- product product item / Update
product / -
9Compound Assignment Operators
- Instead of variable variable op expression
- variable op expression can be used for
- , -, , /, and operators.
- For example
- ct ct 1 ct 1
- time time 1 time - 1
- product product data product data
- n n (x 1) n x1
10The for Statement
- Syntax
- for (initialization expression
- loop repetition condition
- update expression)
- statement
- Example
- for (count_star 0 count_star lt 20
- count_star1 )
- printf()
11The for Statement
- Combines the three loop control steps of
initialization, testing and update in one place
(more complex than while) - Provides a consistent location for each of loop
initialization, testing and update (more popular
that while among the C programmers in industry) - Can be used to count up or down by any interval
12- for (count_mvr 0 /
initialization / - count_mvr lt num_mvrs / loop
condition / - count_mvr 1) / update /
- 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\n", - time_to_mvr)
- total_time time_to_mvr
-
13- include ltstdio.hgt
- int
- main(void)
-
- int time, start
- printf("Enter starting time (an integer) in
secondsgt ") - scanf("d", start)
- printf("\nBegin countdown\n")
- for (time start
- time gt 0
- time - 1)
- printf("T - d\n", time)
-
- printf("Blast-off!\n")
- return (0)
-
- Enter starting time (an integer) in secondsgt 5
- Begin countdown
- T - 5
14- / Conversion of Celsius to Fahrenheit
temperatures / - include ltstdio.hgt
- / Constant macros /
- define CBEGIN 10
- define CLIMIT -5
- define CSTEP 5
- int
- main(void)
-
- / Variable declarations /
- int celsius
- double fahrenheit
- / Display the table heading /
- printf(" Celsius Fahrenheit\n")
15- / Display the table /
- for (celsius CBEGIN
- celsius gt CLIMIT
- celsius - CSTEP)
- fahrenheit 1.8 celsius 32.0
- printf(" 3d 9.2f\n",
celsius, fahrenheit) -
- return (0)
-
- Celsius Fahrenheit
- 10 50.00
- 5 41.00
- 0 32.00
- -5 23.00
16Increment and Decrement operators
- Suppose i 2 and j ?
- Prefix form j i
- increments i and then use it gt i3,j3
- Postfix form j i
- uses i and then increment it gt i3, j2
- Example for n4
- printf ( d,--n) gt 3
- printf ( d,n--) gt 4
- Self-Check 5.4.4 for i 3 and j 9 what are
the results of - n i --j
- m i j--
- p i j
17Conditional loops with for statement
- printf("Number of barrels currently in
tankgt ") - scanf("lf", start_supply)
- for (current start_supply
- current gt min_supply
- current - remov_brls)
- printf(".2f barrels are
available.\n\n", current) - printf("Enter number of gallons
removedgt ") - scanf("lf", remov_gals)
- remov_brls remov_gals /
GALS_PER_BRL - printf("After removal of .2f gallons
(.2f - barrels),\n",
- remov_gals, remov_brls)
-
18Sentinel-Controlled Loop
- Correct Sentinel loop Incorrect Sentinel loop
- 1. sum0 sum0
- 2. get score while
(score!SENTINEL) - 3. while (score!
- SENTINEL) get score
- 4 . sumscore sumscore
- 5. Get score
19Sentinel-Controlled Loop
- / Compute the sum of a list of exam scores. /
- include ltstdio.hgt
- define SENTINEL -99
- int
- main(void)
-
- 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) What is the
result if score entered as 7o? - 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)
20- / Batch Version of Sum of Exam Scores Program /
- include ltstdio.hgt / defines fopen,
fclose, fscanf, -
fprintf, and EOF / - int
- main(void)
-
- FILE inp / input file
pointer / - int sum 0, / sum of scores input
so far / - score, / current score /
- input_status / status value
returned by - fscanf /
- inp fopen("scores.dat", "r")
- printf("Scores\n")
- for (input_status fscanf(inp, "d",
score) - input_status ! EOF
- input_status fscanf(inp, "d",
score)) - printf("5d\n", score)
- sum score
-
21Avoiding Infinite Loops on Faulty Data
- To avoid infinite loop when processing faulty
data the loop in the Sum exam score program can
be modified as the follows -
- for (input_status fscanf(inp, "d", score)
- input_status 1
- input_status fscanf(inp, "d",
score)) - printf("5d\n", score)
- sum score
-
- if (input_status EOF)
- printf(Sum of scores is d\n, sum)
- else
- printf(Error in input, bad character)
-
- Note that in case of reaching EOF input_status is
negative and in case of faulty data input_status
is zero otherwise it is always 1.
22- / Finds the product of nonzero data. /
- include ltstdio.hgt
- define SENT -9999.0
- int
- main(void)
-
- double product 1.0 / product so far
of nonzero data / - int status / status of input
operation / - double data_item / current data
value / - printf("Enter a data item (.1f to quit)gt
", SENT) - for (status scanf("lf", data_item)
- status 1 data_item ! SENT
- status scanf("lf", data_item))
- if (data_item ! 0) /
if statement is nested within the loop / - product data_item
- printf("Enter next data item (.1f to
quit)gt ", SENT) -
- if (status ! 1)
- printf("Error in data list\n")
23Nested Loops
- include ltstdio.hgt
- int
- main(void)
-
- int i, j / loop control variables /
- printf(" I J\n") /
prints column labels / Program output - for (i 1 i lt 4 i) / outer
for loop / - printf("Outer 6d\n", i)
- for (j 0 j lt i j) /
inner loop / - printf(" Inner9d\n", j)
- / end of inner loop /
- / end of outer loop /
- return (0)
-
I J Outer 1 Inner
0 Outer 2 Inner 0 Inner
1 Outer 3 Inner 0 Inner 1
Inner 2
24The do-while Statement
- The first iteration of the loop body occurs
unconditionally (number of repetition is 1 or
more instead of 0 or more in the while statement) - All the statements in the loop are processed
identically - Can be used efficiently for checking the valid
input data
25The do-while Statement
- SYNTAX
- do
- statement
- while ( loop repetition condition)
- Example
- do / Finding the first even number input
/ - status scanf(d num)
- while (status gt0 num 2 !0)
26Flowchart of do-while when using for input
validation
prompt user to get a value for checking
valid input
- value not in desired range
true
false
27do-while When Using for Input Validation
- / Gives an error message on input of an invalid
data type / - printf("Enter minimum and maximum valid valuesgt
") - scanf("dd", n_min, n_max)
- do
- printf("Enter an integer in the range
from d to d inclusivegt ", - n_min, n_max)
- status scanf("d", inval)
- if (status 1)
- error 0
- else
- error 1
- scanf("c", skip_ch)
- printf("\nInvalid charactergtgtcgtgt
Skipping rest of line.\n", - skip_ch)
- do
- scanf("c", skip_ch)
- while (skip_ch ! '\n')
- / Exit
the loop only if the entry is valid / - while (error inval lt n_min inval gt
n_max)
28Flag_conrolled Validation Loop
- do
- error 0 / No errors detected yet
/ - / Get a fraction from the user /
- printf("Enter a common fraction as two
integers separated by ") - printf("a slash\nand press ltentergt\ngt
") - status scanf("dcd", num, slash,
den) - / Validate the fraction /
- if (status lt 3)
- error 1
- printf("Input invalid-please read
directions carefully\n") - else if (slash ! '/')
- error 1
- printf("Input invalid-separate
numerator and denominator") - printf(" by a slash (/)\n")
- else if (den lt 0)
- error 1
- printf("Input invalid-denominator
must be positive\n") -
- do / Discard extra input characters /
29Case Study Computing Radiation Level
- Problem ..Determine how long does it take before
the radiation is down to a safe level of 0.466
millirem a day. Use a chart to display radiation
level for every three days with the message
unsafe and safe after every line. The program
should stop just before the radiation level is
one-tenth of the safe level. - Analysis data requirements
- Constants (SAFE_RAD, SAFETY_FACT),
- Input (init_radiation), Output (day,
radiation_lev)
30Case study Computing Radiation Level
- Design Algorithm
- Initialize day to zero.
- Compute the stopping level
- Prompt user to enter the initial radiation level
- Compute day number and radiation level every 3
days for the levels that exceed the stopping
radiation level - 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
Can we Change it to the for loop?
31Case study Computing Radiation Level
- Implementation
- ............................
- ./ Prompts user to enter initial radiation level
/ - printf("Enter the radiation level (in
millirems)gt ") - scanf("lf", init_radiation)
- / Displays table
/ - printf("\n Day Radiation Status\n
(millirems)\n") - for (radiation_lev init_radiation
- radiation_lev gt min_radiation
- radiation_lev / 2.0)
- if (radiation_lev gt SAFE_RAD)
- printf(" 3d 9.4f
Unsafe\n", day, radiation_lev) - else
- printf(" 3d 9.4f Safe\n",
day, radiation_lev) - day 3
-
- return (0)
- ..
32Case study Computing Radiation Level
- Testing Program result
- Enter the radiation level (in millirems)gt 150.0
- Day Radiation Status
- (millirems)
- 0 150.0000 Unsafe Initial value
- 3 75.0000 Unsafe 75 is 150 / 2,
it shows calculation is ok - 6 37.5000 Unsafe
- 9 18.7500 Unsafe The number of
days increases by 3 - 12 9.3750 Unsafe
- 15 4.6875 Unsafe
- 18 2.3438 Unsafe
- 21 1.1719 Unsafe
- 24 0.5859 Unsafe
- 27 0.2930 Safe
- 30 0.1465 Safe Ending value,
shows the loop exited -
correctly
33How to Debug and Test Programs
- Using debugger programs Quincy debugger
- Debugging without a Debugger
- Diagnostic call to printf
- define DEBUG 1
- if (DEBUG)
- printf(score is d, sum is d\n,score,sum)
- fflush(stdout) / copying the contents of buffer
to associated output device /
34Debugging without a Debugger
- 2- Off-by-One loop errors
- Checking the loop repetition. For example
- for (count 0 count ltn count) sumcount
/executes n1 times/ - for (count 0 count ltn count) sumcount
/executes n times / - Checking the boundaries initial value, end value
and tracing loop with a small loop control
variable
35Common Programming Errors
- Confusion between if , while and for
- Forgetting to put braces for more than two
statements in the loop body - Making mistake when using tests for inequality to
control loop repetition - while (balance !0.0) instead of
- while (balancegt0.0)
- The first while, repeats for negative balance
36Common Programming Errors
- Using instead of in the loop repetition
condition produces infinite loops - do .
- while (again1)
- do-while can be used when there is no possibility
of zero loop - Confusion in compound assignment operators
- a b c is a a (b c) it is not a a b
c - Confusion in increment and decrement operators by
ignoring operators side effect of changing the
value of the operand