Making Decisions

1 / 10
About This Presentation
Title:

Making Decisions

Description:

How to compare data values? Relational operators. How to alter the sequence of program ... P.93, p.96 Blue Book. 6/19/09. B.Ramamurthy. 7. If -else Statement ... –

Number of Views:68
Avg rating:3.0/5.0
Slides: 11
Provided by: kumarm8
Category:
Tags: blue | book | decisions | making | value

less

Transcript and Presenter's Notes

Title: Making Decisions


1
Making Decisions
  • B. Ramamurthy
  • CS113B

2
Introduction
  • Two roads divulged in a yellow wood,
  • And sorry I could not travel both.
  • Robert Frost
  • From The Road Not Taken

3
Decision Statements (General)
  • How to compare data values?
  • Relational operators
  • How to alter the sequence of program execution
    based on the result?
  • If.. Else statements in non-event-driven
    programming
  • Logical operators (, and ! ) and their use.
  • How to deal with multiple choices?
  • Switch statement

4
if Statement
  • An if statement allows a program to choose
    whether or not to execute a following statement.
  • Syntax
  • if (condition)
  • statement
  • Semantics
  • condition is a Boolean expression Something that
    evaluates to True or False.
  • If condition is true then execute the statement
    is executed.

5
Relational Operators
  • Operator Meaning
  • Greater than ?
  • Greater than or equal to?
  • Equal to? (most troublesome)
  • ! Not Equal to ?

6
An Example
  • Condition in the if statement can be formed using
    relational operators which express comparison.
  • P.93, p.96 Blue Book

7
If -else Statement
  • An if-else statement allows a program to do one
    thing if a condition is true and a different
    thing if the condition is false.
  • Syntax
  • if ( condition )
  • statement1
  • else
  • statement2
  • Statements to be executed for if and else can be
    a single statement or multiple statements
    enclosed in .

8
Nested if Statement
  • A body of an if statement could be another if
    statement. This situation is called nested-if.
  • In this case, an else is matched with the most
    recent unmatched if.
  • A nested-if allows a program to make decisions
    based on the results of the previous decision.

9
Dangling Else Problem
  • if ( total Max)
  • if (total
  • System.out.println ( total equals Max but
    is less than sum)
  • else
  • System.out.println (total is not equal to
    Max)

10
Summary
  • In many applications, choices are to be made
    depending on some conditions related to the
    problem. Selection or decision structures are
    used to model such situations.
  • Java supports the implementation of selection
    through the if and switch statements. In this
    discussion we looked at various forms of if
    statements.
Write a Comment
User Comments (0)
About PowerShow.com