34
Decision Making and Branching April 7

Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Embed Size (px)

Citation preview

Page 1: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Decision Making and Branching

April 7

Page 2: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

2

ContentC Language supports the following decision-making statements:

Assignment operators if statement do while statement while statement Conditional operator statement ? :

Page 3: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Assignment operators We have already applied the usual assignment operator. In addition,

C has a set of shorthand assignment operators of the formv op= expr;

is equivalent tov = v op (expr)

Statement with simple assignment operator

Statement with shorthand operator

a = a + 1 a += 1

a = a -1 a -= 1

a = a * (n+1) a =* (n+1)

a = a / (n+1) a =/ (n+1)

a = a % b a %= b

Page 4: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Assignment operators

The use of shorthand assignment operators has advantages: What appears on the left-hand side need not be repeated

and therefore it becomes easier to write. The statement is more concise and easier to read. The statement is more efficient.

value[5*j-2] = value[5*j-2] + delta; value[5*j-2]+= delta;

Page 5: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Use of shorthand operator *= The program prints a sequence of squares of numbers starting

from 2. The statement

a *= a; a = a * a;Replaces the current value of a by its square. When the value of a becomes equal or greater than N (=100) the while is terminated.

Page 6: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Decision making with if statement if is used to control the flow of the execution of statements.

The computer to evaluate the expression first and them depending on whether the value of the expression (relation of condition) is true (non-zero) of false (zero) it transfers the control to a particular statement.

If (test expression)

Test expression?

Entry

False

True

1. if (bank balance is zero) borrow money

2. if (room is dark) turn on lights

3. if (code is 1) person is male

4. if (age is more than 55)person is retired

action

Page 7: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Simple if statement

The statement block may be a single a statement or a group of statements. If the test_expression is true, the statement-block will be executed;

otherwise the statement-block will be skipped and the execution will jump to the statement-x.

The program tests the type of category of the student.If the student belongs to the SPORTS category, then additional bonus_marks are added to his marks before the are printed.

Page 8: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Illustration of simple if statement

The result of the first run is printed as Ratio = -0.75The second run has neither produced any results nor any message. The value (c - d) is equal to zero and therefore, the statements contained in the statement-block are skipped.

To avoid truncation due to integer division.

Page 9: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

9

A bit low-level (assembler)

we need to negate the condition of the jump because we only jump if the condition is false.

eax is 32 bit register

Instruction MeaningJNE Jump if not equal

JE Jump if equal

JG Jump if greater

JLE Jump if less than or equalJL Jump if less than

JGE Jump if greater or equal

cmp compare

C language Assembler

Page 10: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Structure of a do while loopThe general form of the do while loop

do{

statements

}while( expression );

You should restrict the use of do while loops to cases that require at least one iteration:

expression?

Entry

False

True

action

Page 11: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

11

Structure of a do while loop avoid a do while structure of the type shown in the following

pseudocode:

do { ask user if he or she wants to continue some clever stuff } while (answer is yes);

Page 12: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Nested do while loopThe program prints the multiplication table from 1 x 1 to 12 x 10 This program contains two do.... while loops in nested form. The outer loop is controlled by the variable row and executed 12 times. The inner loop is controlled by the variable column and is executed 10 times,

each time the outer loop is executed.

Page 13: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

13

A bit low-level (assembler) The loop body simply executes, the condition is tested at the

end of the loop, and the loop jumps back to the beginning of the loop if the condition is satisfied

C language Assembler

Unlike if statements, Do-While conditions are not reversed

Page 14: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Example: The shoes.c program

The program takes your shoes size in inches and tells you how long your foot is in centimeters.For every new shoe size you have recompile and rerun the program.

Page 15: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

The while Statement

The statement part can be a simple statement with a terminating semicolon, or it can be a compound statement enclosed in braces.

This cycle of test and execution is repeated until expression becomes false (zero).

Each cycle is called an iteration.

expression?

Entry

False

True

actions

Page 16: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

The while loop: shoes2.c1. When the program first reaches the while

statement, it checks to see whether the condition within parentheses is true.

shoe < 13

2. The variable shoe was initialized to 3.0, which certainly is less than 13. Therefore, the condition is true and the program proceeds to the next statement.

shoe = shoe + 1.0;

3. The program returns to the while portion to check the condition.

4. This continues until shoe reaches a value of 14.0. Now the condition

shoe < 14 becomes false because 14.0 is not less than 14.0 (it is

equal). The control passes to the first statement following the while loop.

Page 17: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Example: while and if in useThe program reads in a list of daily low temperatures and reports the total number of entries and the percentage that were below freezing.

Actually, not only q but any non-numeric symbol will cause while to stop! Why?

Page 18: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

An Exit-Condition Loop: do while

The while loop and the for loop are both entry-condition loops.

First do the loop and then check an exit condition.

First check an entry condition and then do

Page 19: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

19

A bit low-level Let’s analyze the while loop again:

First, the loop checks to make sure that x is true. If x is not true, the loop is skipped.

The loop body is then executed, followed by another check: is x still true?

If x is still true, execution jumps back to the top of the loop, and execution continues.

Keep in mind that there needs to be a jump at the bottom of the loop (to get back up to the top), but it makes no sense to jump back to the top, retest the conditional, and then jump back to the bottom of the loop if the conditional is found to be false

Page 20: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

20

A bit low-level (assembler) The processor does the following

1. check the condition. if it is false, go to the end2. perform the loop body3. check the condition, if it is true, jump to 2.4. if the condition is not true, fall-through the end of the loop.

Page 21: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

21

A bit low-level (assembler) But if we to translate that assembly code

back into C, we’d get

Page 22: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Applying De Morgan’s Rule We often come across a situation where logical NOT operator is applied

to a compound logical expression like ! (x && y || !z) A positive logic is always easy to read an comprehend than a negative

logic. In such case, we may apply what is known as De Morgan’s rule to make the total expression positive.

x becomes !x && becomes ||!x becomes x || becomes &&

Remove the parentheses by applying the NOT operator to every logical expression component, while complementing the relational operators

!(x && y || !z) becomes !x || !y && z!(x <= 0 || !condition) becomes x > 0 && condition

Page 23: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

The if … else statement

If the test expression is true, then the true-block statement(s), immediately following the if statements are executed; otherwise, the false-block statement(s) are executed.

In either case, either true-block or false-block will be executed, not both.

Test expression?

Entry

FalseTrue

True-block statement

False-block statement

statement-x

Page 24: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Adding else to the if Statement

C enables to choose between two statements by using the if else form.

No need for second If

if (expression) statement1

else statement2

Page 25: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Examples

The test determines whether or not the student is a boy or girl and increment corresponding variable.

When the value (c – d ) is zero, the ratio is not calculated and the program stops without any message. In such cases we may not know whether the program stopped due to a zero value of some other error.

Page 26: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Example: while in useA program evaluates the power series

The power series contains the recurrence

relationship of the type

Tn = (x/n)Tn-1 for n > 1 and

T1 = x for n = 1, T0 = 1.

If Tn-1 is known, then Tn can be easily found by

multiplying the previous term by x/n .

Then ex = T0 + T1 + T2 +…+ Tn = sum.

f(x) = ex

Page 27: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Use braces to create a single block

If you want more than one statement between the if and the else, you must use braces to create a single block.

Wrong Right

Page 28: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Nesting of if…else statements

When a series of decisions are involved, we may have to use more than one if…else statement in nested form.

Page 29: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Nesting of if…else statements

Example: Here are the rates one company charges for electricity, based on kilowatt-hours (kWh):

First 360 kWh: $0.12589 per kWhNext 320 kWh: $0.17901 per kWhOver 680 kWh: $0.20971 per kWh

Let’s prepare a program to calculate our energy costs using multiple choice statement.

Page 30: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

The electric.c Program

Please enter the kWh used. 580 The charge for 580.0 kWh is $84.70.

Page 31: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

The else if is a variation on what you already knew

You can string together as many else if statements as you need

Page 32: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Pairing else with ifWhen you have a lot of ifs and elses, how does the computer decide which if goes with which else?

Page 33: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

Pairing else with ifConsider the following program fragment:

When is “Sorry, you lose a turn!” printed? a. When number is less than or equal to 6, or b. When number is greater than 12?

In other words, does the else go with the first if or the second?The answer is, the else goes with the second if.

Page 34: Decision Making and Branching April 7. Content C Language supports the following decision-making statements: Assignment operators if statement do while

34

Conditional Expression ?: If Condition is true ? Then value X : Otherwise value YExample:

max = a < b ? b : a;

Find maximum and minimum among three variables r, g, and b.