Professional Documents
Culture Documents
Ch07 - Control Structures PDF
Ch07 - Control Structures PDF
Ch07 - Control Structures PDF
Conditional
• making a decision about which code to execute,
based on evaluated expression
• if
Chapter 7 • if-else
• switch
Control
Structures Iteration
• executing code multiple times,
ending based on evaluated expression
• while
• for
• do-while
13-2
If Example If Statements
if (condition) if (x <= 10)
action; F y = x * x + 5;
condition
T if (x <= 10) {
y = x * x + 5; compound statement;
action z = (2 * y) / 3; both executed if x <= 10
}
if (x <= 10)
only first statement is conditional;
Condition is a C expression, y = x * x + 5;
second statement is
which evaluates to TRUE (non-zero) or FALSE (zero). z = (2 * y) / 3; always executed
Action is a C statement,
which may be simple or compound (a block).
13-3 13-4
1
More If Examples It’s Can Be Nested
if (0 <= age && age <= 11)
if (x == 3)
kids += 1;
if (y != 6) {
z = z + 1;
if (month == 4 || month == 6 || w = w + 2;
month == 9 || month == 11) }
printf(“The month has 30 days.\n”);
is the same as...
if (x = 2) always true,
so action is always executed! if ((x == 3) && (y != 6)) {
y = 5; z = z + 1;
w = w + 2;
This is a common programming error (= instead of ==), }
not caught by compiler because it’s syntactically correct.
13-5 13-6
2
Chaining If’s and Else’s More examples with if - else
if (month == 4 || month == 6 || month == 9 ||
month == 11)
printf(“Month has 30 days.\n”); 1. Input month and year, print out number of days on that
else if (month == 1 || month == 3 || month.
month == 5 || month == 7 || Solution source file
month == 8 || month == 10 ||
month == 12) 2. Solve linear equation:
printf(“Month has 31 days.\n”);
ax + b = 0
else if (month == 2)
printf(“Month has 28 or 29 days.\n”);
else
printf(“Don’t know that month.\n”);
13-9 13-10
3
Examples Examples
Ex1: s = 1 + 2 + … + n Ex2:
#define ESC 27 // Escape button
s = 0;
i = 1; while ( getche() != ESC)
while (i <= n) while (i <= n) ;
{ s += i++;
s += i;
i++; or i = n;
} while (s += i--, i)
;
13-13 13-14
4
Nested Loops Another Nested Loop
Loop body can (of course) be another loop. The test for the inner loop depends on the
counter variable of the outer loop.
/* print a multiplication table */
for (mp1 = 0; mp1 < 10; mp1++) { for (outer = 1; outer <= input; outer++) {
for (mp2 = 0; mp2 < 10; mp2++) for (inner = 0; inner < outer; inner++) {
printf(“%d\t”, mp1*mp2); sum += inner;
}
printf(“\n”); }
}
Braces aren’t necessary,
but they make the code easier to read.
13-17 13-18
13-19 13-20
5
Do-While Examples
do Ex: Using do while for checking
loop_body; loop_body
while (test); // n must be greater than 0
do
test {
T printf (“Input n > 0: “);
F scanf (“%d”, &n);
if (n <= 0)
Executes loop body as long as printf (“Invalid value. Again!\n“);
test evaluates to TRUE (non-zero). } while (n <= 0);
Stop
13-23 13-24
6
Pi: 1st refinement Pi: 2nd refinement
Stop
13-25 13-26
7
Problem 2: Finding Prime Numbers Primes: 1st refinement
Print all prime numbers less than 100. Initialize
• A number is prime if its only divisors are 1 and itself. num = 2
• All non-prime numbers less than 100 will have a divisor Start
between 2 and 10.
F
Initialize num < 100
Start
T
Initialize Print primes Print num
if prime
Stop
13-29 13-30
13-31 13-32
8
Primes: Using a Flag Variable Primes: Complete Code
To keep track of whether number was divisible, #include <stdio.h>
#define TRUE 1
we use a "flag" variable. #define FALSE 0 Optimization: Could put
• Set prime = TRUE, assuming that this number is prime. a break here to avoid some work.
• If any divisor divides number evenly, main () {
int num, divisor, prime; (Section 13.5.2)
set prime = FALSE.
Once it is set to FALSE, it stays FALSE. /* start with 2 and go up to 100 */
• After all divisors are checked, number is prime if for (num = 2; num < 100; num ++ ) {
the flag variable is still TRUE.
prime = TRUE; /* assume num is prime */
/* test whether divisible by 2 through 10 */
Use macros to help readability. for (divisor = 2; divisor <= 10; divisor++)
if (((num % divisor) == 0) && (num != divisor))
#define TRUE 1 prime = FALSE; /* not prime */
#define FALSE 0
if (prime) /* if prime, print it */
printf("The number %d is prime\n", num);
}
13-33 } 13-34
9
More About Switch Problem 3: Searching for Substring
Case expressions must be constant. Have user type in a line of text (ending with linefeed)
case i: /* illegal if i is a variable */ and print the number of occurrences of "the".
If no break, then next case is also executed. Reading characters one at a time
switch (a) { • Use the getchar() function -- returns a single character.
case 1:
printf(“A”); If a is 1, prints “ABC”. Don't need to store input string;
case 2: If a is 2, prints “BC”. look for substring as characters are being typed.
printf(“B”); Otherwise, prints “C”. • Similar to state machine:
default: based on characters seen, move toward success state
printf(“C”); or move back to start state.
} • Switch statement is a good match to state machine.
13-37 13-38
10
Substring: Code (Part 2) Substring: Code (Part 3)
case 1: /* 't' has been matched */ case 2: /* 'th' has been matched */
if (key == 'h') if (key == 'e') {
match = 2; count++; /* increment count */
else if (key == 't') match = 0; /* go to starting point */
match = 1; }
else else if (key == 't') {
match = 0; match = 1;
break; else
match = 0;
break;
}
}
printf("Number of matches = %d\n", count);
}
13-41 13-42
13-43 13-44
11
Homework
And more …
13-45 13-46
In text book
13-47
12