940 likes | 1.68k Views
Decision Making and Branching. April 7. Content. C Language supports the following decision-making statements: Assignment operators if statement d o while statement while statement Conditional operator statement ? :. Assignment operators.
E N D
Decision Making and Branching April 7
Content C Language supports the following decision-making statements: • Assignment operators • ifstatement • do while statement • whilestatement • Conditional operator statement ? :
Assignment operators • We have already applied the usual assignment operator. In addition, C has a set of shorthand assignment operators of the form v op= expr; is equivalent to v = v op (expr)
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;
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.
Decision making with ifstatement • ifis used to control the flow of the execution of statements. If(test expression) 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. Entry • if (bank balance is zero) borrow money • if (room is dark) turn on lights • if (code is 1) person is male • if (age is more than 55) person is retired Test expression? False True action
Simple ifstatement • The statement block may be a single a statement or a group of statements. • If thetest_expressionis true, the statement-block will be executed; otherwise the statement-blockwill 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.
Illustration of simple ifstatement The result of the first run is printed as Ratio = -0.75 The 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.
A bit low-level (assembler) C language Assembler we need to negate the condition of the jump because we only jump if the condition is false. eaxis 32 bit register cmpcompare Instruction Meaning JNE Jump if not equal JE Jump if equal JG Jump if greater JLE Jump if less than or equal JL Jump if less than JGE Jump if greater or equal
Structure of a do while loop The general form of the do while loop Entry do{ statements }while( expression ); action expression? True False You should restrict the use of do while loops to cases that require at least one iteration:
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);
Nested do while loop The program prints the multiplication table from 1 x 1 to 12 x 10 • This program contains two do.... whileloops 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.
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
Example: The shoes.cprogram 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.
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. Entry This cycle of test and execution is repeated until expression becomes false (zero). expression? False Each cycle is called an iteration. True actions
The while loop: shoes2.c • When the program first reaches the while statement, it checks to see whether the condition within parentheses is true. shoe < 13 • 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; • The program returns to the while portion to check the condition. • 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.
Example: while and if in use The 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?
An Exit-Condition Loop: do while The whileloop and the forloop are both entry-condition loops. First check an entry conditionand then do First do the loop and then check an exit condition.
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
A bit low-level (assembler) • The processor does the following • check the condition. if it is false, go to the end • perform the loop body • check the condition, if it is true, jump to 2. • if the condition is not true, fall-through the end of the loop.
A bit low-level (assembler) • But if we to translate that assembly code back into C, we’d get
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. Remove the parentheses by applying the NOT operator to every logical expression component, while complementing the relational operators x becomes !x && becomes || !x becomes x || becomes && !(x && y || !z) becomes !x || !y && z !(x <= 0 || !condition) becomes x > 0 && condition
The if… elsestatement • If the test expression is true, then the true-blockstatement(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. Entry Test expression? True False True-block statement False-block statement statement-x
Adding else to the if Statement C enables to choose between two statements by using the if elseform. if (expression) statement1 else statement2 No need for second If
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.
Example: while in use A program evaluates the power series The power series contains the recurrence relationship of the type Tn = (x/n)Tn-1for n > 1 and T1 = x for n = 1, T0 = 1. If Tn-1is known, then Tncan be easily found by multiplying the previous term by x/n. Then ex =T0+ T1+ T2+…+ Tn= sum. f(x) = ex
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
Nesting of if…else statements • When a series of decisions are involved, we may have to use more than one if…elsestatement in nested form.
Nesting of if…else statements Example: Here are the rates one company charges for electricity, based on kilowatt-hours (kWh): Let’s prepare a program to calculate our energy costs using multiple choice statement.
The electric.c Program Please enter the kWh used. 580 The charge for 580.0 kWh is $84.70.
The else if is a variation on what you already knew You can string together as many else if statements as you need
Pairing else with if When you have a lot of ifs and elses, how does the computer decide which if goes with which else?
Pairing else with if Consider the following program fragment: When is “Sorry, you lose a turn!” printed? • When number is less than or equal to 6, or • 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.
Conditional Expression ?: • If Condition is true ? Then value X : Otherwise value Y Example: max = a < b ? b : a; • Find maximum and minimum among three variables r, g, and b.