Lec4- Selection Structures

Embed Size (px)

Citation preview

  • 8/3/2019 Lec4- Selection Structures

    1/44

    Lec 4SELECTION STRUCTURESAsma Sajid

  • 8/3/2019 Lec4- Selection Structures

    2/44

    Outline

    Review Arithmetic Operators,

    Operator Precedence

    Selection Structure

    If

    If else

    Switch

  • 8/3/2019 Lec4- Selection Structures

    3/44

    Arithmetic Operators in C/C++

    Name Operator Example

    Addition + num1 +

    num2

    Subtraction - initial - spent

    Multiplication * increment * 6

    Division / sum / count

    Modulus % m % n

  • 8/3/2019 Lec4- Selection Structures

    4/44

    Division By Zero

    Division by zero is mathematicallyundefined.

    If you allow division by zero in a

    program, it will cause a fatalerror.Your program will terminate executionand give an error message.

    Non-fatal errors do not causeprogram termination, just produceincorrect results.

  • 8/3/2019 Lec4- Selection Structures

    5/44

    Modulus

    The expression m % n yields theinteger remainder after m is divided byn.

    Modulus is an integer operation -- bothoperands MUST be integers.

    Examples : 17 % 5 = 2

    6 % 3 = 09 % 2 = 1

    5 % 8 = 5

  • 8/3/2019 Lec4- Selection Structures

    6/44

    Uses for Modulus

    Used to determine if an integer value iseven or odd

    5 % 2 = 1 odd 4 % 2 = 0 even

    Logic:

    If you take the modulus by 2 of an

    integer, a result of 1 means the numberis odd and a result of 0 means the

    number is even.

  • 8/3/2019 Lec4- Selection Structures

    7/44

    Arithmetic OperatorsRules of Operator Precedence

    Operator(s) Precedence & Associativity( ) Evaluated first. If nested

    (embedded), innermost first.If on same level, left to right.

    * / % Evaluated second. If there areseveral, evaluated left to right.

    + - Evaluated third. If there areseveral, evaluated left to right.

    = Evaluated last, right to left.

  • 8/3/2019 Lec4- Selection Structures

    8/44

    Using Parentheses

    Use parentheses to change the order inwhich an expression is evaluated.

    a + b * c Would multiply b * c first,then add a to the result.

    If you really want the sum of a and b to bemultiplied by c, use parentheses to force theevaluation to be done in the order you want.

    (a + b) * c Also use parentheses to clarify a complex

    expression.

  • 8/3/2019 Lec4- Selection Structures

    9/44

    Practice With EvaluatingExpressions

    Given integer variables a, b, c, d, and e,where a = 1, b = 2, c = 3, d = 4,

    evaluate the following expressions:

    a + b - c + d

    a * b / c

    1 + a * b % c

    a + d % b - c

    e = b = d + c / b - a

  • 8/3/2019 Lec4- Selection Structures

    10/44

    Selection Structure

    Conditions Relational Operators

    Logical Operators

    if statements Two-Alternatives

    One-Alternative

    Nested If Statements

    switch Statement

  • 8/3/2019 Lec4- Selection Structures

    11/44

    Control Structures

    Control structurescontrol the flow of

    execution in a program or function. Three basic control structures:

    Sequential Flow - this is written as a group ofstatements bracketed by { and }where onestatement follows another.

    Selection control structure - this choosesbetween multiple statements to execute based onsome condition.

    Repetitionthis structure executes a block ofcode multiple times.

    CY N C

    Y

    N

    Sequential Flow Selection control Repetition

  • 8/3/2019 Lec4- Selection Structures

    12/44

    Compound Statements

    A Compound statement or a Code Block iswritten as a group of statements bracketed by {and } and is used to specify sequential flow.{

    Statement_1;

    Statement_2;

    Statement_3;

    }

    Example: themainfunction is surrounded by { }, and

    its statements are executed sequentially.

    Function body also uses compound statement.

  • 8/3/2019 Lec4- Selection Structures

    13/44

    Conditions

    A program chooses among alternative statements bytesting the values of variables. 0 means false

    Any non-zero integer means true, Usually, well use 1 astrue.

    if(a>=b)printf(a is larger or equal to b);

    else

    printf(b is larger);

    Condition - an expression that establishes a criterion foreither executing or skipping a group of statements a>=bis a condition that determines which printf

    statement we execute.

  • 8/3/2019 Lec4- Selection Structures

    14/44

    Relational and Equality

    Operators

    Most conditions that we use to performcomparisons will have one of theseforms:

    variable relational-operatorvariable e.g. a 3

    variable equality-operatorvariable e.g. a ==b

    variable equality-operatorconstant e.g. a !=

    10

  • 8/3/2019 Lec4- Selection Structures

    15/44

    Relational and Equality

    Operators

    Operator Meaning Type

    < less than relational

    > greater than relational= greater than or equal to relational

    == equal to equality

    != not equal to equality

  • 8/3/2019 Lec4- Selection Structures

    16/44

    Logical Operators

    logical expressions - expressions that use conditionalstatements and logical operators. && (and)

    A && B is true if and only if both A and B are true

    || (or)

    A || B is true if either A or B are true ! (not) !(condition) is true if condition is false, and false if

    condition is true This is called the logical complement or negation

    Examples (salary < 10000) || (dependants > 5)

    (temperature > 40.0) && (humidity > 90)

    !(temperature > 90.0)

  • 8/3/2019 Lec4- Selection Structures

    17/44

    Truth Table && Operator

    A B A && B

    False (zero) False (zero) False (zero)

    False (zero) True (non-zero) False (zero)

    True (non-zero) False (zero) False (zero)

    True (non-zero) True (non-zero) True (non-zero)

  • 8/3/2019 Lec4- Selection Structures

    18/44

    Truth Table || Operator

    A B A || B

    False (zero) False (zero) False (zero)

    False (zero) True (non-zero) True (non-zero)

    True (non-zero) False (zero) True (non-zero)

    True (non-zero) True (non-zero) True (non-zero)

  • 8/3/2019 Lec4- Selection Structures

    19/44

    Operator Table ! Operator

    A !A

    False (zero) True (non-zero)

    True (non-zero) False (zero)

  • 8/3/2019 Lec4- Selection Structures

    20/44

    Remember!

    && operator yields a true result onlywhen both its operands are true.

    || operator yields a false result only

    when both its operands are false.

  • 8/3/2019 Lec4- Selection Structures

    21/44

    Operator PrecedenceSome C/C++ operators in order of precedence(highest to lowest).

    Their associativityindicatesin what order operators of equal precedence

    in anexpression are applied.

  • 8/3/2019 Lec4- Selection Structures

    22/44

    Writing English Conditions inC Make sure your C condition is logically

    equivalent to an equivalent Englishstatement.

    x and y are greater than z(x > z) && (y > z) (valid)

    x && y > z (invalid)

  • 8/3/2019 Lec4- Selection Structures

    23/44

    Character Comparison

    C allows character comparison usingrelational and equality operators.

    During comparison Lexicographic

    (alphabetical) order is followed. (See Appendix

    for a complete list of ASCII values).

    9 >= 0 // True

    a < e // True

    a

  • 8/3/2019 Lec4- Selection Structures

    24/44

    Logical Assignment

    You can assign an int type variable a non zerovalue for trueor zero for false.Ex: even = (n%2 == 0);

    if(even) { do something }

  • 8/3/2019 Lec4- Selection Structures

    25/44

    Complementing a condition

    We can complement a logical expression by

    preceding it with the symbol ! We can also complement a single condition by

    changing its operator. Example : The complements of (age == 50) are

    !(age == 50) and (age != 50)

    Relational operators should change as follows:, < to >= and so on

  • 8/3/2019 Lec4- Selection Structures

    26/44

    No { }?

    if (rest_heart_rate > 56)cout

  • 8/3/2019 Lec4- Selection Structures

    27/44

    One Alternative?

    You can also write the if statementwith a single alternative that executesonly when the condition is true.

    if( a

  • 8/3/2019 Lec4- Selection Structures

    28/44

    Nested if Statements

    So far we have used if statements to code decisionswith one or two alternatives.

    A compound statement may contain more ifstatements.

    if(x > 0)

    num_pos = num_pos + 1;

    else if(x < 0)

    num_neg = num_neg + 1;

    else

    num_zero = num_zero + 1;

    Comparison of Nested if and

  • 8/3/2019 Lec4- Selection Structures

    29/44

    Comparison of Nested if andSequences of ifs

    Beginning programmers sometime prefer to use asequence of if statements rather than a single nested ifstatement

    if (x > 0)

    num_pos = num_pos + 1;if (x < 0)

    num_neg = num_neg + 1;

    if (x == 0)

    num_zero = num_zero +1;

    This is less efficient because all three of the conditionsare always tested.

    In the nested if statement, only the first condition is testedwhen

    xis positive.

  • 8/3/2019 Lec4- Selection Structures

    30/44

    Example

    Given a persons salary, we want to calculate the tax due

    by adding the base tax to the product of the percentagetimes the excess salary over the minimum salary for thatrange.

    Salary Range Base tax Percentage of Excess

    0.00 14,999.99 0.00 15

    15,000.00 29,999.99 2,250.00 18

    30,000.00 49,999.99 5,400.00 22

    50,000.00 79,999.99 11,000,00 27

    80,000.00150,000.00

    21,600.00 33

  • 8/3/2019 Lec4- Selection Structures

    31/44

    if( salary < 0.0)

    tax = -1.0;

    else if( salary < 15000.00)

    tax = 0.15 * salary;

    else if( salary < 30000.00)

    tax = (salary 15000.00)*0.18 + 2250.00;

    else if( salary < 50000.00)tax = (salary 30000.00)*0.22 + 5400.00;

    else if( salary < 80000.00)tax = (salary 50000.00)*0.27 + 11000.00;

    else if( salary

  • 8/3/2019 Lec4- Selection Structures

    32/44

    Order of Conditions in a Multiple-Alternative Decision

    When more than one condition in a multiple-alternative decision is true, only the task followingthe first true condition executes.

    Therefore, the order of the conditions can affect

    the outcome. If we know that salary range 30,000 - 49,999 are

    much more likely than the others, it would bemore efficient to test first for that salary range.For example,if ((salary>30000.00) && (salary

  • 8/3/2019 Lec4- Selection Structures

    33/44

    Nested if Statements with More ThanOne Variable

    In most of our examples, we have usednested if statements to test the value of asingle variable.

    Consequently, we have been able to write

    each nested if statement as a multiple-alternative decision. If several variables are involved in the

    decision, we cannot always use a multiple-alternative decision.

    The next example contains a situation inwhich we can use a nested if statement asa filter to select data that satisfies severaldifferent criteria.

  • 8/3/2019 Lec4- Selection Structures

    34/44

    ExampleThe Department of Defense would like a

    program that identifies single males between theages of 18 and 26, inclusive.

    Identify single males(18-26)

    Use a nested if statement whoseconditions test the next criteriononly if all previous criteria tested

    were satisfied.

    1.Combine all of the tests into asingle logical expression.

    2. In the next nested if statement,the call to cout executes onlywhen all conditions are true.

  • 8/3/2019 Lec4- Selection Structures

    35/44

    Common if statement errors

    if crsr_or_frgt == Ccout

  • 8/3/2019 Lec4- Selection Structures

    36/44

    Switch statements

    The switch statement is a better way ofwriting a program when a series of if-else ifoccurs.

    The switch statement selects one of several

    alternatives. The switch statement is especially useful

    when the selection is based on the value ofa single variable or of a simple expression This is called the controlling expression

    In C, the value of this expression may be oftype int or char, but not of type double.

    Example of a switch Statement with Type char Case Labels

  • 8/3/2019 Lec4- Selection Structures

    37/44

    Example of a switch Statement with Type char Case Labels/* Determines the class of Ship given its class ID */#include int main(void) {

    char classID;

    printf("Enter class id [a, b, c or d]: ");scanf("%c", &classID);

    switch (classID) {case 'B':case 'b':

    printf("Battleship\n");break;

    case 'C':case 'c':

    printf("Cruiser\n");break;

    case 'D':case 'd':

    printf("Destroyer\n");

    break;case 'F':case 'f':

    printf("Frigate\n");break;

    default:printf("Unknown ship class %c\n", classID);

    }

    return 0;}

  • 8/3/2019 Lec4- Selection Structures

    38/44

    Explanation of Example

    This takes the value of the variable class andcompares it to each of the cases in a top downapproach.

    It stops after it finds the first case that is equal to thevalue of the variable class.

    It then starts to execute each line of the code followingthe matching case till it finds a break statement or theend of the switch statement.

    If no case is equal to the value of class, then the

    default case is executed. default case is optional. So if no other case is equal to the value

    of the controlling expression and there is a default case, thendefault case is executed. If there is no default case, then theentire switch body is skipped.

  • 8/3/2019 Lec4- Selection Structures

    39/44

    Remember !!! The statements following a case label may be one or

    more C statements, so you do not need to make multiplestatements into a single compound statement usingbraces.

    You cannot use a string such as Cruiser or Frigate asa case label.

    It is important to remember that type int and char values maybe used as case labels, type double values cannot be used.

    Another verycommon error is the omission of the breakstatement at the end of one alternative. In such a situation, execution falls through into the next

    alternative.

    Forgetting the closing brace of the switch statement bodyis also easy to do.

    In the book it says that forgetting the last closing bracewill make all following statements occur in the default

    case, but actually the code will not compile on mostcompilers.

  • 8/3/2019 Lec4- Selection Structures

    40/44

    Nested if versus switch

    Advantages of if: It is more general than a switch

    It can be a range of values such as x < 100

    A switch can not compare doubles

    Advantages of switch: A switch is more readable

    Use the switch whenever there are ten orfewer case labels

    C P i E

  • 8/3/2019 Lec4- Selection Structures

    41/44

    Common Programming Errors

    Consider the statement:

    if (0

  • 8/3/2019 Lec4- Selection Structures

    42/44

    More Common Errors

    Dont forget to parenthesize the condition. Dont forget the { and } if they are needed

    C matches each else with the closest unmatched if,so be careful so that you get the correct pairings ofif and else statements.

    In switch statements, make sure the controllingexpression and case labels are of the samepermitted type.

    Remember to include the default case for switch

    statements. Dont forget your { and } for the switch statement.

    Dont forget your break statements!!!

  • 8/3/2019 Lec4- Selection Structures

    43/44

    Assignment #1

    1.Find solution of equations of motion. vf=vi+at

    S= vit+1/2 at2

    2aS= vf2 - vi2

    2. What should be appropriate input andoutput data type for these equations. Justify

    your answer.

    Assignment format

  • 8/3/2019 Lec4- Selection Structures

    44/44

    Assignment format

    Heading size-14 bold, font style= times

    new roman or Arial Normal text size=12

    Dont use word art in your assignment.

    Assignment title page should contain Assignment #1

    Name:

    Roll no: Semester:

    Submitted to:

    College of Computer Science & Information