G51PR1 - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

G51PR1

Description:

The 'if' statement, provides decision making capabilities. ... 2. Cleveland Gibbon, Writing Typographically Sound Programs with Ceilidh, LTR ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 30
Provided by: OPA6
Category:
Tags: g51pr1 | gibbon

less

Transcript and Presenter's Notes

Title: G51PR1


1
G51PR1
  • Introduction to Programming I
  • 2000-2001
  • University of Nottingham
  • Unit 3 Conditionals

2
Overview
  • Simple if statement
  • if else statements
  • Further Alternatives
  • Possible Conditions
  • Nesting if statements
  • Ambiguity
  • Simple switch statements
  • switch Example
  • case values
  • Program Layout
  • CourseWork Exercises

3
Simple if statements
  • The if statement, provides decision making
    capabilities.
  • It causes selected statements to be executed if a
    certain condition evaluates to true at that
    point in the program.
  • Syntax
  • if (condition)
  • statement
  • If the boolean condition is true, the statement
    is executed if it is false, the statement is
    skipped

4
Simple if statements
  • int Radius, Result 0
  • Radius UserInput.readInt() // user code
  • if ( Radius gt 0 )
  • Result Radius Radius
  • System.out.println("Radius is positive")
  • // end if Radius gt 0
  • System.out.println(Radius " " Result)

5
Simple if statements
  • The condition to be tested appears in parentheses
    after the word "if", and the statement or
    statements whose execution is determined by the
    condition are contained within curly braces. If
    the condition does not hold, everything up to
    the next "" is ignored, and program execution
    continues after the "". In this example, if the
    radius value read in is positive, the program
    then executes in order the statements
  • Result Radius Radius
  • System.out.println("Radius is positive")
  • System.out.println(Radius " " Result)
  • If the value read in is not positive, the
    statement in the braces following the "if"
    condition will be ignored, and the program will
    execute the single statement
  • System.out.println(Radius " " Result)

6
if ... else" statements
  • If the condition does not hold, we may wish to
    execute some different statements as alternatives
    to the "if" statements.
  • Syntax
  • if (condition) statement else
    statement

false
true
statement1
statement2
7
if ... else" statements
  • int Money
  • int Deposits 0 , Withdrawals 0
  • Money UserInput.readInt()
  • if ( Money gt 0 )
  • System.out.println("Deposit.")
  • Deposits Money Deposits
  • else
  • // if Money lt 0
  • System.out.println("Withdrawal.")
  • Withdrawals Money - Withdrawls
  • // end if else Money gt 0
  • System.out.println("Transaction noted.")

8
"If ... else ..." statements
  • If the quantity read is positive, the program
    then executes
  • System.out.println("Deposit.")
  • Deposits Money Deposits
  • System.out.println("Transaction noted.")
  • If the quantity is zero or negative, the program
    executes
  • System.out.println("Withdrawal.")
  • Withdrawals Money - Withdrawals
  • System.out.println("Transaction noted.")

9
"If ... else ..." statements
  • The careful layout of programs becomes more
    important as the programs become more structured.
    Some people prefer to put the braces on separate
    lines as in
  • if ( Radius gt 0 )
  • ....
  • ....
  • // end of Radius gt 0
  • else
  • // if Radius lt 0
  • ....
  • ....
  • // end if else

10
Further alternatives
  • We can add further alternatives to an "if"
    statement if we require.
  • if ( Radius gt 100 ) // Radius gt 100
  • ....
  • else if ( Radius gt 10 ) // Radius gt 10 and
    Radius lt 100
  • ....
  • else if ( Radius gt 1 ) // Radius gt 1 and
    Radius lt 10
  • ....
  • else // Radius lt 1
  • ....
  • // end if Radius various values
  • The tests in the if statements are executed
    exactly in the order in which they are
    encountered. The first test here is "Radius gt
    100" if this is false, the second test if
    executed, testing whether "Radius gt 10", so that
    this is effectively the test "Radius lt 100
    Radius gt 10", since we know that the first test
    is false.

11
Possible conditions (logical expressions)
  • We looked at the format of conditions in unit 2,
    when we were discussing expressions in general.
  • // Test equality, use double equals
  • if ( code 3 ) ....
  • // Two tests ANDed together
  • if ( Radius gt 0 Radius lt 10 ) ....
  • // Two tests ORed together
  • if ( code 0 code 1 ) ....

12
Possible Conditions
  • Note that the AND ("") and OR ("") forms, are
    lazy left-to-right operators. This means that the
    expressions to be AND-ed together are evaluated
    from left to right, one at a time, and as soon as
    one is found which is FALSE, evaluation finishes
    and a FALSE result is returned. The remaining
    expressions are not evaluated at all. Only the
    minimum amount of work is done to determine the
    result. It is then perhaps safe to write
  • if ( Div gt 0.001 Total/Div lt
    100 ) ...
  • since we can never get division be zero.
  • Similarly with OR, the expressions are evaluated
    left-to-right, and as soon as one is found which
    is TRUE, evaluation ceases and a TRUE result is
    returned.

13
Nesting "if" statements
  • "if" statements can be nested if that is what the
    program logic requires.
  • if ( Radius gt 0 )
  • if ( Result gt 0 ) // Radius gt 0 and Result gt
    0
  • ....
  • else // Radius gt 0 and Result lt 0 here
  • ....
  • // end if else Result gt 0
  • else // not Radius gt 0
  • if ( Result gt 0 ) // Radius lt 0 and Result
    gt 0
  • ....
  • else // Radius lt 0 and Result lt 0
  • ....
  • // end if else Result gt 0
  • // end if else Radius gt 0

14
Ambiguity
  • We have specified above that you must always use
    curly braces after an "if" condition and after
    the "else". The Java official definition states
    that the curly braces are essential only if there
    is more than one statement to be executed as a
    result of the condition. Many commercial users of
    Java insist, as we do, that the curly braces
    should always be there.
  • If you don't use curly braces, the following can
    be ambiguous (to the reader)
  • if ( Radius gt 0 )
  • if ( Result gt 0 )
  • xxx
  • else
  • yyy

15
Ambiguity
  • The above executes as
  • if ( Radius gt 0 )
  • if ( Result gt 0 )
  • xxx
  • else
  • yyy
  • But can be easily mistaken for
  • if ( Radius gt 0 )
  • if ( Result gt 0 )
  • xxx
  • else
  • yyy

16
Ambiguity
  • These two have quite different effects. In the
    case when, for example, "Radius gt 0" and not
    "Result gt 0", the first will execute "yyy", the
    second will have no effect. If we have "Radius lt
    0" (the first condition is FALSE) and "Result gt
    0", the first example will have no effect, while
    the second would execute "yyy".
  • The two are thus quite different in their effect.
    It is a good principle always to use curly
    braces, and to put a comment after any closing
    curly brace which is not close to its opening
    partner. An example might be
  • if ( Radius gt 0 )
  • ...
  • ...
  • // end if Radius gt 0
  • Our rule (enforced by the CourseMaster marking
    system) will be that a closing curly brace must
    have a comment if it is more than 10 lines after
    its opening curly brace. This ensures that you
    see a comment on the computer terminal screen if
    the complete "if" statement is unlikely to fit
    onto one screenful of information.

17
switch statements
  • The "if" statement essentially gives a choice
    between two alternatives. We may sometimes need a
    choice between a larger number of possibilities.
    The "switch" construct allows for any number of
    different actions to be taken dependent of the
    value of an integer calculation.
  • The syntax of the switch statement is
  • switch (expression)
  • case value1
  • statement
  • case value2
  • statement
  • case

18
switch example
  • int inputValue
  • inputValue UserInput.readInt()
  • switch ( inputValue )
  • case 0 // if "inputValue" is 0
  • do_this()
  • break
  • case 4 // if "inputValue" is 4
  • do_that()
  • break
  • case 7 // if "inputValue" is 7
  • do_the_other()
  • break
  • default // if "inputValue" is anything else
  • something_else()
  • // end switch( inputValue )
  • The expression you switch on must be one of int,
    byte, char, short or long.

19
case Values
  • The value after the word "case" must be a
    constant, you could not put case PartType, where
    PartType is a variable. You must put either an
    explicit constant (i.e. the numeric value 7), or
    a declared final, for example static final
    int insPerFoot 12
  • Two "case" labels can be adjacent. In this case,
    the two specified values will cause the same code
    to be executed.
  • Don't forget the "break" statements where you
    need them. You will normally want control to
    leave the "switch" statement at the end of each
    separate "case".
  • The "default" entry is optional, but often is
    included.

20
Character switch example
  • char commandChar
  • commandChar UserInput.readChar()
  • switch ( commandChar )
  • // Perhaps 'e' for "edit"
  • case 'e'
  • edit()
  • break
  • // Perhaps 'l' for list/print
  • case 'l'
  • case 'p'
  • print()
  • break
  • // Some other character
  • default
  • System.out.println("Don't understand "
    commandChar)
  • // end switch( commandChar )

21
Character switch example
  • Note again the careful indentation, and the
    comment after the closing curly brace.
  • It is also possible to omit the break statements
    on the rare occasions when you wish to cause code
    to follow through as in this example, although
    this is regarded by many as bad practice.
  • In this case, 'r' causes "run" 'c' causes
    "compile" then "run" 'e' causes "edit" then
    "compile" then "run"
  • case 'e' edit()
  • case 'c' compile()
  • case 'r' run()
  • break

22
Program layout
  • As we learn new constructs, programs become more
    complex, and the neat layout of programs becomes
    more important. Our automatic marking system will
    check your layout.The suggested form of layout
    for "if" statements and "switch" statements is as
    shown in the above examples. Generally, we indent
    each set of statements from "" to "" about 3-4
    spaces more than the outer code.
  • if ( Radius gt 0 )
  • Result Radius Radius
  • System.out.print(Positive Radius")

if ( Radius gt 0 ) // end if Radius gt 0
Result Radius Radius
System.out.print("Positive Radius") // end if
Radius gt 0
23
Program layout
  • if ( Money gt 0 )
  • System.out.println("Deposit.)"
  • Deposits Money
  • else // if Money lt 0
  • System.out.println("Withdrawal.)"
  • Withdrawals - Money
  • // end if else Money gt 0
  • if ( Money gt 0 )
  • System.out.println("Deposit.)"
  • Deposits Money
  • else if ( Money gt 100 )
  • System.out.println("Money greater than 100.
    ")
  • else // if Money lt 0
  • System.out.println("Withdrawal.")
  • Withdrawals - Money
  • // end if else Money gt 0

24
Program layout
  • if ( x gt 10 )
  • System.out.println("x positive")
  • if ( y gt 0 )
  • System.out.println("y positive too")
  • else
  • System.out.println("x is but y isn't")
  • // end if x positive

25
Program layout
  • switch ( inputValue )
  • case 0 // if "inputValue" is 0
  • do_this()
  • break
  • case 3
  • case 4 // if "inputValue" is 3 or 4
  • do_that()
  • break
  • case 7 // if "inputValue" is 7
  • do_the_other()
  • break
  • default // if "inputValue" is anything else
  • yet_else()
  • // end switch ( inputValue )

26
Program layout
  • CourseMaster marking has the same rules for ""
    and "" and for "(" and ")". If the matching
    symbols will fit on the same line, all is well.
    You are permitted
  • Cash Number ( CostPerItem Overhead )
  • if ( x gt 0 ) System.out.println("Message ")
  • If the matching pair will not fit on one line,
    then the closing one must start a line further
    down, lining up with the start of the line
    containing the opening one
  • Cash Number (
  • CostPerItem Overhead // perhaps a longer
    expression
  • )
  • if ( x gt 0 )
  • System.out.println("A long message -- A long
    message -- A long message ")
  • // and a comment here

27
Coursework exercise marking
  • The exercises in this unit are marked partly on
    dynamic correctness, partly on typographic
    layout, and sometimes you will see a heading
    Features. For dynamic correctness and typographic
    layout, earlier comments apply (see the end of
    unit 2 notes1 and the Typographic Layout
    paper2 and the program layout section above).
  • The features mark is problem specific, and
    concerns the items for which a teacher would look
    by eye if marking your programs by hand. For
    example, if the problem involves converting
    centimetres to inches, the explicit conversion
    factor 2.54 should appear as a single global
    constant, it should NOT appear more than once, it
    should NOT appear in the program. If you are
    converting minutes to hours, the constant 60
    should appear only once, as a global constant,
    and it is bad practice to use the constant 59.
  • Always use gt 60 rather than gt 59 when the
    value which represents the factor which concerns
    us (the number of minutes in an hour) is 60, not
    59.
  • So, if you loose marks on features you must stop
    and think of all the good programming practices
    you have been taught, and decide which principle
    you have broken.

28
References
  • 1. Eric Foxley, Programming in C - Basics, LTR
    Report, Computer Science Dept, Nottingham
    University, 1996.
  • 2. Cleveland Gibbon, Writing Typographically
    Sound Programs with Ceilidh, LTR Report, Computer
    Science Dept, Nottingham University, 1995.

29
Summary
  • Simple switch statements
  • switch Example
  • case values
  • Program Layout
  • CourseWork Exercises
  • Simple if statements
  • if else statements
  • Further Alternatives
  • Possible Conditions
  • Nesting if statements
  • Ambiguity
Write a Comment
User Comments (0)
About PowerShow.com