Control Structures - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

Control Structures

Description:

So far, we have worked with sequential algorithms, where each ... A video rental shop uses the following type classification scheme for movie video cassettes: ... – PowerPoint PPT presentation

Number of Views:197
Avg rating:3.0/5.0
Slides: 42
Provided by: maryelai
Category:

less

Transcript and Presenter's Notes

Title: Control Structures


1
Control Structures
  • In structured programming, we use three basic
    control structures
  • Sequence
  • Selection
  • Repetition
  • So far, we have worked with sequential
    algorithms, where each instruction is executed
    once, immediately after the one above it

2
Selection
  • We use selection to handle making choices
  • A condition that is evaluated to be either true
    or false determines the next action

True
False
Is a gt b?
Print Yes
Print No
IF 1 is greater than 2 THEN Print Yes ELSE
Print No ENDIF
3
Selection
  • Needed in most programs (if they do anything
    interesting)
  • What are some examples of decisions a program
    might have to make?

4
Selection - Variations
  • Simple selection - IF, THEN, ELSE
  • Simple selection with null false branch - IF,
    THEN
  • Combined selection - AND, OR
  • Nested selection
  • Case structure

5
Simple Selection
  • IF account_balance lt 300 THEN service_charge
    5.00ELSE service_charge 2.00ENDIF

6
Simple Selection in C
  • if (condition) statement block
  • else statement block
  • if (x lt y)
  • small x
  • else
  • small y

7
Truth and Falsehood in C
  • The value of false in C is 0.
  • Everything else is true.
  • if (x-x) printf(This will never be
    printed\n) else printf(This will always
    be printed\n)

8
Relational Operators
  • Used to test the relationship between two
    expressions or two variables
  • Condition evaluates as
  • false (0)
  • true (non-zero integer)
  • Note that stringing relational operators together
    doesnt work
  • 2 lt x lt 7 will be true when x is 8 (Why?)

9
Cs Relational Operators
  • Equal uses two equal signs
  • gt Greater than
  • lt Less than
  • gt Greater than or equal to
  • lt Less than or equal to
  • ! Not equal
  • Note no space in two character operators

10
Examples
x 500, y 300 if (xy) if (x gt 100) if (y
gt250)
if (x ! 500) if ((x y) gt 700) if ((x / 2) lt
99)
11
Logical Operators
  • Used to combine or negate expressions containing
    logical operators.
  • used with compound conditions

and or ! not
12
Logical Operators
and -- if ((x 5) (y ! 10)) both
conditions must be true for statement to
evaluate as true or -- if ((x 7) (y gt
10)) either condition can be true for
statement to evaluate is true.
Only evaluates as false if both false not
-- ! if (! (x gt 7)) reverses the value of
expression to its immediate right. same
as if (x lt 7)
13
Logical or Boolean Expression
  • Condition that is true (any non 0) or false (0)
  • if (n ! 0), same as if (n)
  • testing for truth same as testing for non-zero
    value
  • You can use a preprocessor directive to give
    meaningful names to 1 and 0
  • define TRUE 1
  • define FALSE 0
  • can write if (n TRUE)

14
Order of Precedence
( ) Parentheses highest , -, !
(not) Unary , /, Multiplication, Division
,Modulus , - Addition, Subtraction lt lt
gt gt Greater than, less than, or equal
! Equal, not equal And Or Assignment
statement lowest Rule Use parentheses to
make evaluation order clear
15
Conditions Practice
  • 1. Given a 12, b 6, c 8
  • true or false? ((a lt b)(b ! c)
  • (!(a lt b) !(b gt c))
  • ((a gt b)(a gt c)(b gt
    c))
  • 2. What would the values of a, b, and c need to
    be for this statement to be true? (use 1,2,3)
  • ((a gtc b gt c) a lt b))

16
Selection - Variations
  • Simple selection - IF, THEN, ELSE
  • Simple selection with null false branch - IF,
    THEN
  • Combined selection - AND, OR
  • Nested selection
  • Case structure

17
Simple Selection
  • IF account_balance lt 300 THEN service_charge
    5.00ELSE service_charge 2.00ENDIF

18
Simple Selection in C
  • if (condition) statement block
  • else statement block
  • if (x lt y)
  • small x
  • else
  • small y

19
Simple Selection with Null False Branch (no ELSE)
  • Used when nothing needs to be done if the
    condition is false
  • IF student_attendance part_time THEN add 1 to
    part_time_countENDIF

20
In C
  • if (condition) statement block
  • if (num1 gt num2)
  • printf(Its bigger\n)

21
Combined Selection
  • IF student_attendance part_time AND
    student_gender female THEN add 1 to
    fem_part_time_countENDIF
  • IF (record_code 23 OR update_code delete)
    AND account_balance zero THEN delete customer
    recordENDIF

22
In C
  • if (num1 gt num3 num2 gt num3) printf(The
    third is the smallest\n)
  • if ((record_code 23 update_code D)
    account_balance 0)
  • delete_record(current_record)

23
Nested Selection (Linear)
  • IF record_code A THEN increment
    counter_AELSE IF record_code B THEN
    increment counter_B ELSE IF record_code
    C increment counter_C ELSE increment
    error_counter ENDIF ENDIFENDIF

24
Nested Selection (Non-linear)
  • IF student_attendance part_time THEN IF
    student_gender female THEN IF student_age
    gt 21 THEN add 1 to mature_fem_pt_students
    ELSE add 1 to young_fem_pt_students
    ENDIF ELSE add 1 to male_pt_students ENDIF
    ELSE add 1 to full_time_studentsENDIF

25
Nested if statements
if (expression) statement if true else
if (expression) statement if true
else statement if false
if (expression) statement if true else if
(expression) statement if true else
statement if false
Rule else matches nearest unmatched if that
precedes it
26
Consider this if (num lt 10) if (num gt 3)
printf (d is between 3 and 10, num)
else printf (d is less than 3,
num) if (num lt 10) / braces allow else to go
with first if / if (num gt 3) printf
(d is between 3 and 10, num) else
printf (d is greater than 10, num)
27
AND and Nested IFs
  • IF student_attendance part_time THEN IF
    student_age gt 21 THEN increment
    mature_pt_student ENDIFENDIF
  • IF student_attendance part_time AND
    student_age gt 21 THEN increment
    mature_pt_studentENDIF

28
Selection Example
  • A program is required to read a customers name,
    a purchase amount and a tax code. The tax code
    has been validated and will be one of the
    following 0 tax exempt (0) 1 state sales tax
    only (3) 2 federal and state sales tax
    (5) 3 special sales tax (7)The program must
    then compute the sales tax and the total amount
    due and print the customers name, purchase
    amount, sales tax and total amount due.

29
Group Problem
  • Design an algorithm which will prompt an operator
    for a students serial number and the students
    exam score out of 100. Your program is then to
    match the exam score to a letter grade and print
    the grade to the screen. The letter grade is to
    be calculated as follows 90 and
    above A 80-89 B 70-79 C 60-69 D belo
    w 60 F

30
Problem 1
  • Write a nested if statement that displays an
    average daily temperature with a label for the
    type of day. If the average is 75 or above, it
    is a warm day. If the average is between 50 and
    74, it is a moderate day. If below 50, it is
    considered a cold day.

31
Problem 2
  • A company is raising its employees salaries
    based on the following tableemployee
    status years of service percent
    raiseFull-time Less than 5 years 4.0Full-time
    5 or more years 5.0Part-time Less than 5
    years 2.5Part-time 5 or more years 3.0If
    employee_status value is 1, the employee is
    full-time. If it is 2, the employee is
    part-time. Write a single nested if statement
    that computes the new salary of an employee given
    his or her employee_status, years_of_service, and
    salary.

32
Pseudocode Case Structure
  • Alternative to some linear nested if statements
  • CASE OF some variable value_1 statement
    block_1 value_2 statement block_2 value_n
    statement block_n other statement
    block_otherENDCASE

33
Case Example
  • CASE OF record_code A increment
    counter_A B increment counter_B C
    increment counter_C other increment
    error_counterENDCASE

34
C Switch Statement
switch (expression) case
val1 statements break case val2
statements break case val3 statements
break default statements
Note expression must evaluate to an integral
type int, char, short, long val1, val2, and
val3 are integral constant expressions default
is the case executed if none of the other cases
are satisfied. It is not required but is usually
a good idea.
35
break
  • The break statement causes an immediate exit from
    the switch
  • Without the break, execution falls through from
    each case to the next
  • This enables us to specify multiple values that
    should cause the same code to be executed without
    having to repeat the code
  • But we must be careful to include the break where
    it belongs
  • A break is recommended, though not required, at
    the end of the last case

36
Example
  • switch (tax_code) case 0 tax_rate
    0.0 break case 1 tax_rate
    0.03 break case 2 tax_rate
    0.05 break case 3 tax_rate
    0.07 break default
    printf(tax_code out of range\n)

37
Switch example
switch (num 10) case 0 printf
(Ones digit is zero\n) break case
1 printf (Ones digit is one\n)
break case 2 printf (Ones digit is
two\n) break default
printf (Ones digit is d\n,num 10)

38
Switch example
switch (CountFrom) case 5 printf
(5\n) case 4 printf (4\n) case 3
printf (3\n) case 2 printf (2\n)
case 1 printf (1\n)
printf (Ignition\n) printf (Blast
off!\n)
39
Selection Example with CASE
  • A program is required to read a customers name,
    a purchase amount and a tax code. The tax has
    been validated and will be one of the
    following 0 tax exempt (0) 1 state sales tax
    only (3) 2 federal and state sales tax
    (5) 3 special sales tax (7)The program must
    then compute the sales tax and the total amount
    due and print the customers name, purchase
    amount, sales tax and total amount due.

40
Problem 3
  • A video rental shop uses the following type
    classification scheme for movie video cassettes
  • Code Movie Category
  • A Action and Adventure
  • C Comedy
  • D Drama
  • F Family
  • H Horror
  • M Musical
  • Any other code value is an error and should print
    out a warning message. Write a switch statement
    that tests the value of type_code and increments
    the number of videos for the appropriate category

41
Group Problem 2
  • Design a program which will read two numbers and
    an integer code from the screen. The value of
    the code should be 10, 20, 30, or 40. If the
    value of the code is 10 then compute the sum of
    the two numbers. If the code is 20 compute the
    difference (first minus second). If the code is
    30, compute the product of the two numbers. If
    the code is 40 and the second number is not zero,
    then compute the quotient (first number divided
    by second). The program is then to print the two
    numbers, the integer code and the computed result
    to the screen. If problems arise with the data
    (incorrect codes or zero divisors), print
    appropriate error messages.
Write a Comment
User Comments (0)
About PowerShow.com