Ch07 - Control Structures PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Control Structures

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

If-else Matching Else with If


if (condition) Else is always associated with closest unassociated if.
action_if; T F
condition if (x != 10)
else
action_else; if (y > 3)
z = z / 2;
action_if action_else else
z = z * 2;
is the same as... is NOT the same as...
Else allows choice between if (x != 10) { if (x != 10) {
two mutually exclusive actions without re-testing condition. if (y > 3) if (y > 3)
z = z / 2; z = z / 2;
else }
z = z * 2; else
13-7
} z = z * 2; 13-8

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

While Infinite Loops


while (test) The following loop will never terminate:
loop_body; F
test
x = 0;
T while (x < 10)
printf(“%d ”, x);
loop_body

Loop body does not change condition,


so test never fails.

Executes loop body as long as This is a common programming error


test evaluates to TRUE (non-zero). that can be difficult to find.

Note: Test is evaluated before executing loop body.


13-11 13-12

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

For Example For Loops


for (init; end-test; re-init) /* -- what is the output of this loop? -- */
init for (i = 0; i <= 10; i ++)
statement
printf("%d ", i);

F /* -- what does this one output? -- */


test letter = 'a';
for (c = 0; c < 26; c++)
T printf("%c ", letter+c);

loop_body /* -- what does this loop do? -- */


Executes loop body as long as
numberOfOnes = 0;
test evaluates to TRUE (non-zero). for (bitNum = 0; bitNum < 16; bitNum++) {
Initialization and re-initialization re-init if (inputValue & (1 << bitNum))
code includedin loop statement. numberOfOnes++;
}

Note: Test is evaluated before executing loop body.


13-15 13-16

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

Example For vs. While


In general:

For loop is preferred for counter-based loops.


• Explicit counter variable
• Easy to see how counter is modified each loop

While loop is preferred for sentinel-based loops.


• Test checks for sentinel value.

Either kind of loop can be expressed as the other,


so it’s really a matter of style and readability.

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

Note: Test is evaluated after executing loop body.


13-21 13-22

Problem Solving in C Problem 1: Calculating Pi


Calculate  using its series expansion.
Stepwise Refinement
• as covered in Chapter 6
User inputs number of terms.
...but can stop refining at a higher level of abstraction.
4 4 4 4
  4       ( 1)n 1 
Same basic constructs 3 5 7 2n  1
• Sequential -- C statements
• Conditional -- if-else, switch
Start Evaluate
• Iterative -- while, for, do-while Series
Initialize
Output
Results
Get Input

Stop
13-23 13-24

6
Pi: 1st refinement Pi: 2nd refinement

Start Initialize Initialize


iteration count iteration count T count F
Initialize is odd
for loop
F F
count<terms count<terms
Get Input
T T subtract term add term

Evaluate Evaluate Evaluate


Series next term next term
add term
Output
count = count+1 count = count+1 if-else
Results

Stop
13-25 13-26

Pi: Code for Evaluate Terms Pi: Complete Code


#include <stdio.h>

for (count=0; count < numOfTerms; count++) { main() {


if (count % 2) { double pi = 0.0;
/* odd term -- subtract */ int numOfTerms, count;
pi -= 4.0 / (2 * count + 1);
printf("Number of terms (must be 1 or larger) : ");
} scanf("%d", &numOfTerms);
else {
for (count=0; count < numOfTerms; count++) {
/* even term -- add */ if (count % 2) {
pi += 4.0 / (2 * count + 1); pi -= 4.0 / (2 * count + 1); /* odd term -- subtract */
} }
else {
pi += 4.0 / (2 * count + 1); /* even term -- add */
Note: Code in text is slightly different, }
but this code corresponds to equation. printf("The approximate value of pi is %f\n", pi);
}
13-27 13-28

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

Print primes Stop num = num + 1

Stop
13-29 13-30

Primes: 2nd refinement Primes: 3rd refinement


Initialize
Initialize
num = 2
Divide num by Divide num by divisor = 2
2 through 10 2 through 10
F
num < 100 F
divisor <= 10
no F no F
T divisors? divisors?
T
Print num T T Clear flag if
if prime num%divisor > 0
Print num Print num
num = num + 1 divisor =
divisor + 1

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

Switch evaluate Switch Example


expression /* same as month example for if-else */
switch (expression) {
case const1: switch (month) {
case 4:
action1; break; case 6:
case const2: = const1? action1 case 9:
T case 11:
action2; break;
F printf(“Month has 30 days.\n”);
default: break;
action3; case 1:
= const2? action2 case 3:
} T /* some cases omitted for brevity...*/
F printf(“Month has 31 days.\n”);
break;
action3 case 2:
printf(“Month has 28 or 29 days.\n”);
Alternative to long if-else chain. break;
If break is not used, then default:
printf(“Don’t know that month.\n”);
case "falls through" to the next.
13-35 } 13-36

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

Substring: State machine to flow chart Substring: Code (Part 1)


#include <stdio.h>
read char
no
other match main() {
char key; /* input character from user */
't' T int match = 0; /* keep track of characters matched */
match = 0 if 't', match=1
int count = 0; /* number of substring matches */
matched F
't' other if 'h', match=2 /* Read character until newline is typed */
T while ((key = getchar()) != '\n') {
't' match = 1 if 't', match=1
'h' else match=0
/* Action depends on number of matches so far */
F switch (match) {
't' matched
other if 'e', count++
'th'
T and match = 0
match = 2 case 0: /* starting - no matches yet */
'e' if 't', match=1
if (key == 't')
F else match=0
match = 1;
't'
matched other break;
'the'
increment
count 13-39 13-40

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

Break and Continue Example


break; What does the following loop do?
• used only in switch statement or iteration statement for (i = 0; i <= 20; i++) {
• passes control out of the “smallest” (loop or switch) statement if (i%2  0) continue;
containing it to the statement immediately following printf("%d ", i);
• usually used to exit a loop before terminating condition occurs
(or to exit switch statement when case is done)
}

continue; What would be an easier way to write this?


• used only in iteration statement
• terminates the execution of the loop body for this iteration
• loop expression is evaluated to see whether another
iteration should be performed
• if for loop, also executes the re-initializer What happens if break instead of continue?

13-43 13-44

11
Homework
And more …

13-45 13-46

In text book

13.1 -> 13.18 except for 13.5 and 13.11

13-47

12

You might also like