Week 6 C Programming
Week 6 C Programming
Computer Programming I
Week 6
Program Control – I
Dr. Yucel Tekin
Objectives
• Learn the essentials of counter-controlled iteration.
• Use the for and do…while iteration statements to execute statements repeatedly.
• Understand multiple selection using the switch selection statement.
• Use the break and continue statements to alter the flow of control.
• Use logical operators to form complex conditions in control statements.
• Avoid the consequences of confusing the equality and assignment operators.
Outline
4.1 Introduction
4.2 Iteration Essentials
4.3 Counter-Controlled Iteration
4.4 for Iteration Statement
4.5 Examples Using the for Statement
4.6 switch Multiple-Selection Statement
4.2 Iteration Essentials
• Most programs involve iteration (or looping)
• A loop repeatedly executes statements while some loop-continuation condition remains
true
– Counter-controlled iteration uses a control variable to count the number of iterations for
a group of instructions to perform
– When the correct number of iterations has been completed, the loop terminates
– Use sentinel values to control iteration if the precise number of iterations isn’t known in
advance
– A sentinel value indicates “end of data”
– The sentinel is entered after all regular data items have been supplied
4.3 Counter-Controlled Iteration (1 of 3)
• Counter-controlled iteration requires:
– the name of a control variable,
– the initial value of the control variable,
– the increment (or decrement) by which the control variable is modified in
each iteration, and
– the loop-continuation condition that tests for the final value of the control
variable to determine whether looping should continue.
• Consider Fig 4.1, which displays the numbers from 1 through 10.
ure
4.3 Counter-Controlled Iteration (2 of 3)
1. // fig04_01.c
2. // Counter-controlled iteration.
3. #include <stdio.h>
4.
5. int main(void) {
6. int counter = 1; // initialization
7.
8. while (counter <= 10) { // iteration condition
9. printf("%d ", counter);
10. ++counter; // increment
11. }
12.
13. puts("");
14. }
4.3 Counter-Controlled Iteration (3 of 3)
1. // fig04_02.c
2. // Counter-controlled iteration with the for statement.
3. #include <stdio.h>
4.
5. int main(void) {
6. // initialization, iteration condition, and increment
7. // are all included in the for statement header.
8. for (int counter = 1; counter <= 10; ++counter) {
9. printf("%d ", counter);
10. }
11.
12. puts(""); // outputs a newline
13. }
4.4 for Iteration Statement (2 of 11)
• First, defines the control variable counter and initializes it to 1.
• The initial value of counter is 1, so the condition is true, and the for statement executes its
printf statement to display counter’s value
• Next, the for statement executes ++counter, then re-tests the loop-continuation condition
• The control variable is now equal to 2, so the condition is still true, and the for statement executes
its printf statement again.
Control Variables Defined in a for Header Exist Only Until the Loop
Terminates
• When you define the control variable in the for header before the first
semicolon (;), the control variable exists only until the loop terminates
• Access the control variable after the for statement’s closing right brace (})
is a compilation error
4.4 for Iteration Statement (5 of 11)
Off-By-One Errors
• If we had written the loop-continuation condition counter <= 5
as counter < 5, then the loop would execute only four times
• This is a common logic error called an off-by-one error
• Using a control variable’s final value in a while or for statement
condition and using the <= relational operator can help avoid off-by-one errors
4.4 for Iteration Statement (6 of 11)
• General Format of a for Statement
for (initialization; loopContinuationCondition; increment) {
statement
}
– initialization names the control variable and provides its initial value
– loopContinuationCondition determines whether the loop should
continue executing
– increment modifies the control variable’s value after executing the
statement so the loop-continuation condition eventually becomes false.
– The two semicolons are required
4.4 for Iteration Statement (7 of 11)
• Infinite loops occur when the loop-continuation condition never becomes
false
– Ensure that you do not place a semicolon immediately after a while
statement’s header
– In a counter-controlled loop, ensure that you increment (or decrement)
the control variable so the loop-continuation condition eventually
becomes false
– In a sentinel-controlled loop, ensure that the sentinel value is
eventually input
4.4 for Iteration Statement (8 of 11)
Expressions in the for Statement’s Header Are Optional
• All three expressions in a for header are optional
• If you omit the loopContinuationCondition, the condition is always true
• You might omit the initialization expression if the program initializes the
control variable before the loop
• You might omit the increment expression if the program calculates the
increment in the loop’s body or if no increment is needed
4.4 for Iteration Statement (9 of 11)
Increment Expression Acts Like a Standalone Statement
• The for statement’s increment acts like a standalone statement at the end of the
for’s body
• So, the following are all equivalent:
– counter = counter + 1
– counter += 1
– ++counter
– counter++
• The increment in a for statement’s increment expression may be negative and the
loop counts downward.
4.4 for Iteration Statement (10 of 11)
Using a for Statement’s Control Variable in the Statement’s
Body
• Programs frequently display the control-variable value or use it
in calculations in the loop body
• Although the control variable’s value can be changed in a for
loop’s body, avoid doing so, because this practice can lead to
subtle errors
4.4 for Iteration Statement (11 of 11)
for Statement Flowchart
4.5 Examples Using the for Statement
1. Vary the control variable from 1 to 100 in increments of 1.
– for (int i = 1; i <= 100; ++i)
2. Vary the control variable from 100 to 1 in increments of -1
– for (int i = 100; i >= 1; --i)
3. Vary the control variable from 7 to 77 in increments of 7.
– for (int i = 7; i <= 77; i += 7)
4. Vary the control variable from 20 to 2 in increments of -2
– for (int i = 20; i >= 2; i -= 2)
5. Vary the control variable over the values 2, 5, 8, 11, 14 and 17.
– for (int j = 2; j <= 17; j += 3)
• Output:
– Sum is 2550
4.5 Examples Using the for Statement—
Compound-Interest Calculations (1 of 11)
• A person invests $1000.00 in a savings account yielding 5% interest. Assuming all
interest is left on deposit in the account, calculate and print the amount of money in
the account at the end of each year for 10 years. Use the following formula for
determining these amounts:
– a p(1 r)n
• where
– p is the original amount invested (i.e., the principal, $1000.00 here),
r is the annual interest rate (for example, .05 for 5%),
n is the number of years, which is 10 here, and
a is the amount on deposit at the end of the nth year.
4.5 Examples Using the for Statement—
Compound-Interest Calculations (2 of 11)
• The solution (Fig 4.4) uses a counter-controlled loop to perform the same
ure
3. #include <stdio.h>
4. #include <math.h>
5.
6. int main(void) {
9.
15.
18.
21. }
22. }
4.5 Examples Using the for Statement—
Compound-Interest Calculations (5 of 11)
• Output:
Year Amount on deposit
1 1050.00
2 1102.50
3 1157.63
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89
4.5 Examples Using the for Statement—
Compound-Interest Calculations (6 of 11)
• You must include <math.h> (line 4) to use pow and C’s other math functions
• Function pow requires two double arguments, but variable year is an
integer
• The math.h file includes information that tells the compiler to convert the
year value to a temporary double representation before calling pow
• This information is contained in pow’s function prototype
4.5 Examples Using the for Statement—
Compound-Interest Calculations (7 of 11)
Formatting Numeric Output
• This program used the conversion specification %21.2f to print variable amount’s value
• 21 in the conversion specification denotes the field width in which the value will be
printed
– 21 specifies that the value printed will use 21 character positions
• If the number of characters displayed is less than the field width, then the value will be
right-aligned with leading spaces
– Particularly useful for aligning the decimal points of floating-point values
• To left-align a value in a field, place a (minus sign) between the % and the field width
4.5 Examples Using the for Statement—
Compound-Interest Calculations (8 of 11)
Floating-Point Number Precision and Memory Requirements
• float typically requires four bytes of memory with approximately seven significant digits
• double typically requires eight bytes of memory with approximately 15 significant digits—about double
the precision of floats
• The C standard states the minimum sizes of each type and indicates that type double provides at least
as much precision as float and that type long double provides at least as much precision as
double
https://en.cppreference.com/w/c/language/arithmetic_types
–
4.5 Examples Using the for Statement—
Compound-Interest Calculations (9 of 11)
Floating-Point Numbers Are Approximations
• Floating-point numbers often arise as a result of division—when we divide
10 by 3, the result is the infinitely repeating sequence 3.3333333…. with
the sequence of 3s repeating infinitely
• The computer allocates only a fixed amount of space to hold such a value,
so the stored floating-point value can be only an approximation
• C’s floating-point types suffer from representational error
• Assuming that floating-point numbers are represented can lead to
incorrect results
4.5 Examples Using the for Statement—
Compound-Interest Calculations (10 of 11)
A Warning about Displaying Rounded Values
• Here’s what can go wrong when using floating-point numbers to represent dollar amounts
displayed with two digits to the right of the decimal point
• Two calculated dollar amounts stored in the machine could be 14.234 (rounded to 14.23
for display purposes) and 18.673 (rounded to 18.67 for display purposes)
• When these amounts are added, they produce the internal sum 32.907, which would
typically be rounded to 32.91 for display purposes
• Thus, your output could appear as
14.23
•
+ 18.67
32.91
• then displayed d’s value with many digits of precision to the right of the decimal
point
• The output showed 123.02 as 123.0199999…, which is another example of a
representational error
• This is a common problem in many programming languages
4.6 switch Multiple-Selection Statement (1 of 17)
E
4.6 switch Multiple-Selection Statement (8 of 17)
Incorrect letter grade entered. Enter a new grade.
D
A
b
^Z
• We represent characters in this program as int because EOF has an integer value
• Testing for the symbolic constant EOF, rather than 1, makes programs more portable
4.6 switch Multiple-Selection
Statement (11 of 17)
• The C standard specifies the minimum range of values for each integer type
– The actual range may be greater, depending on the implementation