[go: up one dir, main page]

0% found this document useful (0 votes)
2 views50 pages

Week 6 C Programming

The document outlines the objectives and key concepts of counter-controlled iteration in programming, focusing on the use of for and do...while statements, as well as the switch selection statement. It explains the structure and components of loops, including initialization, conditions, and increments, while also addressing common errors such as off-by-one mistakes and infinite loops. Additionally, it provides examples of practical applications, such as summing even integers and calculating compound interest, while emphasizing the importance of understanding floating-point representation in calculations.

Uploaded by

maher sawsak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views50 pages

Week 6 C Programming

The document outlines the objectives and key concepts of counter-controlled iteration in programming, focusing on the use of for and do...while statements, as well as the switch selection statement. It explains the structure and components of loops, including initialization, conditions, and increments, while also addressing common errors such as off-by-one mistakes and infinite loops. Additionally, it provides examples of practical applications, such as summing even integers and calculating compound interest, while emphasizing the importance of understanding floating-point representation in calculations.

Uploaded by

maher sawsak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CENG 103 – 105 – 107

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)

• int counter = 1; // initialization


– names the control variable (counter), defines it as an integer,
reserves memory space for it, and sets its initial value to 1
• ++counter; // increment
– increments counter by 1 at the end of each loop iteration

• Counter <= 10;

– tests whether the value of the control variable is less than or


equal to 10
• Loop terminates when counter exceeds 10
4.4 for Iteration Statement (1 of 11)
• for statement handles all the details of counter-controlled iteration

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.

• Next, it tests counter <= 10

• 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.

• This continues until counter becomes 11


– At this point, the loop-continuation condition is false and iteration terminates.
4.4 for Iteration Statement (3 of 11)
for Statement Header Components
4.4 for Iteration Statement (4 of 11)

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)

6. Vary the control variable over 44, 33, 22, 11, 0.


– for (int j = 44; j >= 0; j -= 11)
4.5 Examples Using the for Statement—
Summing the Even Integers From 2 to 100
1. // fig04_05.c
2. // Summation with for.
3. #include <stdio.h>
4.
5. int main(void) {
6. int sum = 0; // initialize sum
7.
8. for (int number = 2; number <= 100; number += 2) {
9. sum += number; // add number to sum
10. }
11.
12. printf("Sum is %d\n", sum);
13. }

• 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

calculation for each of the 10 years the money remains on deposit


• The for statement executes its body 10 times, varying a control variable from
1 to 10 in increments of 1.
• C does not include an exponentiation operator
• The call pow(x, y) calculates x raised to the yth power
• pow returns a double value, which we then multiply by principal
4.5 Examples Using the for Statement—
Compound-Interest Calculations (3 of 11)
1. // fig04_06.c

2. // Calculating compound interest.

3. #include <stdio.h>

4. #include <math.h>

5.

6. int main(void) {

7. double principal = 1000.0; // starting principal

8. double rate = 0.05; // annual interest rate

9.

10. // output table column heads

11. printf("%4s%21s\n", "Year", "Amount on deposit");


4.5 Examples Using the for Statement—
Compound-Interest Calculations (4 of 11)
13. // calculate amount on deposit for each of ten years

14. for (int year = 1; year <= 10; ++year) {

15.

16. // calculate new amount for specified year

17. double amount = principal * pow(1.0 + rate, year);

18.

19. // output one table row

20. printf("%4d%21.2f\n", year, amount);

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

• .2 specifies the precision (i.e., the number of decimal 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

• C treats floating-point values such as 3.14159 as type double by default

• Such values in the source code are known as floating-point literals


• C also has type long double, typically stored in 12 or 16 bytes of memory

• 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

• but a person adding the numbers as displayed would expect 32.90


4.5 Examples Using the for Statement—
Compound-Interest Calculations (11 of 11)
Common Dollar Amounts Can Have Floating-Point Representational Errors
• Even simple dollar amounts can have representational errors when they’re stored as
doubles

• To see this, we created a simple program with the declaration


– double d = 123.02;

• 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)

• Occasionally, an algorithm will contain a series of decisions that test a


variable or expression separately for each of the integer values it may
assume, then perform different actions
• This is called multiple selection
• C provides the switch multiple-selection statement
• Consists of a series of case labels, an optional default case and
statements to execute for each case
• Figure 4.5 uses switch to count the number of each different letter grade
students earned on an exam
4.6 switch Multiple-Selection Statement (2 of 17)
1. // fig04_07.c
2. // Counting letter grades with switch.
3. #include <stdio.h>
4.
5. int main(void) {
6. int aCount = 0;
7. int bCount = 0;
8. int cCount = 0;
9. int dCount = 0;
10. int fCount = 0;
11.
12. puts("Enter the letter grades.");
13. puts("Enter the EOF character to end input.");
14. int grade = 0; // one grade
15.
4.6 switch Multiple-Selection Statement (3 of 17)
16. // loop until user types end-of-file key sequence
17. while ((grade = getchar()) != EOF) {
18.
19. // determine which grade was input
20. switch (grade) { // switch nested in while
21. case 'A': // grade was uppercase A
22. case 'a': // or lowercase a
23. ++aCount;
24. break; // necessary to exit switch
25. case 'B': // grade was uppercase B
26. case 'b': // or lowercase b
27. ++bCount;
28. break;
4.6 switch Multiple-Selection Statement (4 of 17)
29. case 'C': // grade was uppercase C
30. case 'c': // or lowercase c
31. ++cCount;
32. break;
33. case 'D': // grade was uppercase D
34. case 'd': // or lowercase d
35. ++dCount;
36. break;
37. case 'F': // grade was uppercase F
38. case 'f': // or lowercase f
39. ++fCount;
40. break;
4.6 switch Multiple-Selection Statement (5 of 17)
41. case '\n': // ignore newlines,
42. case '\t': // tabs,
43. case ' ': // and spaces in input
44. break;
45. default: // catch all other characters
46. printf("%s", "Incorrect letter grade entered.");
47. puts(" Enter a new grade.");
48. break; // optional; will exit switch anyway
49. } // end switch
50. } // end while
51.
4.6 switch Multiple-Selection Statement (6 of 17)
52. // output summary of results
53. puts("\nTotals for each letter grade are:");
54. printf("A: %d\n", aCount);
55. printf("B: %d\n", bCount);
56. printf("C: %d\n", cCount);
57. printf("D: %d\n", dCount);
58. printf("F: %d\n", fCount);
59. }
4.6 switch Multiple-Selection Statement (7 of
17)

Enter the letter grades.

Enter the EOF character to end input.

E
4.6 switch Multiple-Selection Statement (8 of 17)
Incorrect letter grade entered. Enter a new grade.
D
A
b
^Z

Totals for each letter grade are:


A: 3
B: 2
C: 3
D: 2
F: 1
4.6 switch Multiple-Selection Statement (9 of 17)

Reading Character Input


• while ((grade = getchar()) != EOF) {
– The parenthesized assignment executes first
– getchar function (from <stdio.h>) reads one character
from the keyboard
– Characters are normally stored in char variables
– C can store characters in variables of any integer type
– Function getchar returns as an int the character that the
user entered
4.6 switch Multiple-Selection Statement (10 of 17)
Assignments Have Values

• Assignments as a whole actually have a value (whatever is assigned)

• EOF is a symbol whose acronym stands for “end of file”


• We use EOF (which normally has the value 1) as a sentinel value

• User types a system-dependent “end of file” keystroke combination

• EOF is a symbolic integer constant defined in the <stdio.h> header

• If the value assigned to grade is equal to E O F, the program terminates

• 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)

Entering the EOF Indicator


• On Linux/UNIX/macOS systems
– Ctrl + d
– This notation means to simultaneously press both the Ctrl key and the d
key
• On other systems, such as Microsoft Windows
– Ctrl + z
– You also need to press Enter on Windows.
4.6 switch Multiple-Selection Statement (12 of
17)

switch Statement Details


• Keyword switch is followed by a controlling expression in parentheses
• This expression’s value is compared with each case label
• When a match occurs, the statements for that case execute
• A break statement exits the switch immediately
• Without a break statement the cases run together.
• This feature—called fall through—is rarely useful
4.6 switch Multiple-Selection
Statement (13 of 17)
default Case
• If no match occurs, the default case executes
• Always include a default case; otherwise, values not explicitly tested in a
switch will be ignored
• Although the case clauses and the default case clause can occur in any
order, place the default clause last
4.6 switch Multiple-Selection Statement: switch
Statement Flowchart
4.6 switch Multiple-Selection Statement (14 of 17)
Ignoring Newline, Tab and Blank Characters in Input

41. case '\n': // ignore newlines,


42. case '\t': // tabs,
43. case ' ': // and spaces in input
44. break;

• cause the program to skip newline, tab and blank characters


• Reading characters one at a time can cause problems
• Pressing Enter places the newline character in the input
• Often, this newline (and other whitespace characters) must be specifically ignored to
make the program work correctly
4.6 switch Multiple-Selection Statement (15 of 17)

Constant Integral Expressions


• When using the switch statement, each case can test only a constant
integral expression
• A character constant can be represented as the specific character in single
quotes
• Must be enclosed within single quotes to be recognized as character
constants—characters in double quotes are recognized as strings.
• Integer constants are simply integer values
4.6 switch Multiple-Selection Statement (16 of
17)

Notes on Integral Types


• Portable languages like C must have flexible data-type sizes
• C short int (abbreviated as short) and long int (abbreviated as long)
• There also are unsigned variations of all the integral types for non-negative
integers
• C also provides type long long int (abbreviated as long long).
4.6 switch Multiple-Selection Statement (17 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

– short int: 32767 to  32767


– long int: 2147483647 to  2147483647
– int’s range is greater than or equal to that of short and less than or
equal to that of long
– signed char can represent integers in the range
–127 to  127
Questions

You might also like