decision making and branching (cont.)

28
Decision Making and Branching (cont.) April 14

Upload: elmer-booker

Post on 17-Jan-2018

217 views

Category:

Documents


0 download

DESCRIPTION

Introduction C Language supports the following decision-making statements: for statement switch statement

TRANSCRIPT

Page 1: Decision Making and Branching (cont.)

Decision Making and Branching (cont.)

April 14

Page 2: Decision Making and Branching (cont.)

Introduction C Language supports the following decision-making statements:

for statement switch statement

Page 3: Decision Making and Branching (cont.)

3

The for loop The general form of the for loop is

The execution of the for statement is as follows Initialization of the control variables (i = 1 or count = 0) The value of the control variable is tested using the test-condition

(i < 10). If the condition is true, the body of the loop is executed, otherwise the loop is terminated.

The control variable is updated (i++, or i = 2*i + 1)

for (initialization; test-condition; update){body of the loop

}

Page 4: Decision Making and Branching (cont.)

4

The for loop Consider the following segment of a program

If there is only one line in the for loop body, we can omit { }

This for loop is executed 10 times and prints the digits 0 to 9 in one line.

Page 5: Decision Making and Branching (cont.)

5

The for loop The for statement allows for negative increments.

It also allows more complex update rules

Page 6: Decision Making and Branching (cont.)

6

Connection to while loopFrom a CPU point of view the for loop is a while-loop with an initial state, a condition, and an iterative instruction.

Page 7: Decision Making and Branching (cont.)

7

Compiler optimization Often in for() loops you assign an initial constant value in A (for example x

= 0), and then compare that value with another constant in B (for example x < 10)

Most optimizing compilers will be able to notice that the first time x IS less than 10, and therefore there is no need for the initial if(B) statement

In such cases, the compiler will simply generate the following sequence:

Page 8: Decision Making and Branching (cont.)

The For Loop and Comma Operator

The comma operator extends the flexibility of the for loop by enabling you to include more than one initialization or update expression in a single for loop specification

Page 9: Decision Making and Branching (cont.)

9

A comma operator exampleA program that prints first-class postage rates

Comma Operator

Page 10: Decision Making and Branching (cont.)

A for loop example program The program uses a for loop to print the "Powers of 2" table for

the power 0~20 The program evaluates the value p = 2n successively multiplying

2 by itself n times and q = 2-n = 1/p Note that we have declared p as a long int and q as a double.

Page 11: Decision Making and Branching (cont.)

11

A for loop example (cont.)

Page 12: Decision Making and Branching (cont.)

Zeno Meets the for Loop The Greek philosopher Zeno once argued that an arrow

will never reach its target. First, he said, the arrow covers half the distance to the target. Then it has to cover half of the remaining distance. Then it still has half of what's left to cover, ad infinitum. Because the journey has an infinite number of parts, Zeno argued, it would take the arrow an infinite amount of time to reach its journey's end.

• Let's take a quantitative approach and suppose that it takes the arrow 1 second to travel the first half. Then it would take 1/2 second to travel half of what was left, 1/4 second to travel half of what was left next, and so on. You can represent the total time by the following infinite series:

1 + 1/2 + 1/4 + 1/8 + 1/16 +....

Page 13: Decision Making and Branching (cont.)

Arrow problem

1 + 1/2 + 1/4 + 1/8 + 1/16 +....

The program finds the sum of the first few terms

Page 14: Decision Making and Branching (cont.)

Arrow problem (Output)

14

Page 15: Decision Making and Branching (cont.)

Nested Loops A nested loop is one loop inside another. A common use for nested loops is to display data in rows and

columns.

Page 16: Decision Making and Branching (cont.)

A Nested VariationThe inner loop may behave differently each cycle depending on the outer loop.

Page 17: Decision Making and Branching (cont.)

17

Infinite loop Infinite loop can implemented in many ways

for(;1;){…} do{…}while(1) while(1){…}

Generally these all loops are reduced to a simple unconditional jump statement:

Notice that some non-optimizing compilers will produce nonsensical code for this:

Page 18: Decision Making and Branching (cont.)

Loop flow controls: break; and continue;

C uses two different orders to control loop’s flow break – escapes from the nearest outer loop continue –

inside “while” and “do” loop: switches program execution to test condition,

inside “for” loop: switches program execution to “for” loop step and then to condition test (also applies for nearest outer loop)

Page 19: Decision Making and Branching (cont.)

Loop flow controls: break; and continue;

19

Possible algorithm enhancements (decreasing number of iterations) It is enough to loop n/2 times, better, only till sqrt(n). Test if the number is dividable with 2, and if it isn’t, test inside loop

if the number is dividable with odd numbers bigger than 2.

The program checks whether the entered value is prime or not.

Page 20: Decision Making and Branching (cont.)

The use of the break statement.The program reads a list of positive values and calculates their average. The for loop is written to read 1000 values.

Page 21: Decision Making and Branching (cont.)

The use of continue statement.The program evaluates the square root of a series of numbers and prints the results. The process stops when the number 9999 is typed in.

Page 22: Decision Making and Branching (cont.)

22

Branching condition order switch – case Control passes to the statement whose case constant-expression

matches the value of switch ( expression ). The switch statement can include any number of case instances, but

no two case constants within the same switch statement can have the same value.switch( expression ){

case const_expression1:

orders1;break;

case const_expression2:

orders2; break;

default : ordersN;}

Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break statement transfers control out of the body.

If no cases match then default case will be executed.

Page 23: Decision Making and Branching (cont.)

Branching condition order switch – case

Use instead of multisided if selectionPay attention: if the keyword break isn’t stated inside case block; program continues to next case block in the list!

If break; was to be left-out from every case block, for given grade 3 (example), the result would be false and following:

Page 24: Decision Making and Branching (cont.)

24

Comparing if-else and switch

Page 25: Decision Making and Branching (cont.)

25

General guidelines for Writing Multiway Selection Statements

Avoid compound negative statements. Use positive statements wherever possible.

Keep logical expressions simple. We cam achieve this using nested if statements (Keep It Simple and Short)

Try to code the normal/anticipated condition first. The choice between the nested if and switch statements is a

matter of individual’s preference. A good rule of thumb is to use the switch when alternative paths are thee to ten.

Use proper indentations. Have the habit of using default clause in switch statements. Group the case labels that have similar actions.

Page 26: Decision Making and Branching (cont.)

Review questionsWhat errors can you find?

Page 27: Decision Making and Branching (cont.)

Review questionsWhat will each of the following programs print?

Page 28: Decision Making and Branching (cont.)

Review questionsGiven the input "Go west, young man!", what would each of the following programs produce for output?