Presentation is loading. Please wait.

Presentation is loading. Please wait.

Decision Making and Branching (cont.)

Similar presentations


Presentation on theme: "Decision Making and Branching (cont.)"— Presentation transcript:

1 Decision Making and Branching (cont.)
April 14

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

3 for (initialization; test-condition; update){
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 }

4 The for loop Consider the following segment of a program
This for loop is executed 10 times and prints the digits 0 to 9 in one line. If there is only one line in the for loop body, we can omit { }

5 The for loop The for statement allows for negative increments.
It also allows more complex update rules

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

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:

8 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

9 A comma operator example
A program that prints first-class postage rates Comma Operator

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

11 A for loop example (cont.)

12 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/

13 Arrow problem The program finds the sum of the first few terms
 1 + 1/2 + 1/4 + 1/8 + 1/

14 Arrow problem (Output)

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

16 A Nested Variation The inner loop may behave differently each cycle depending on the outer loop.

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:

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

19 Loop flow controls: break; and continue;
The program checks whether the entered value is prime or not. 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.

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

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

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.

23 Branching condition order switch – case
Use instead of multisided if selection Pay 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:

24 Comparing if-else and switch

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.

26 Review questions What errors can you find?

27 Review questions What will each of the following programs print?

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


Download ppt "Decision Making and Branching (cont.)"

Similar presentations


Ads by Google