Flowchart for If Else Statement - PowerPoint

Document Sample
Flowchart for If Else Statement - PowerPoint Powered By Docstoc
					Control Structures
    Chapters 4, 5, & 6 Overview
                      Today’s Lesson Plan
   Discuss labs, quizzes, and TDA topics (10 min)
       Discussion posts should cite sources
   Class Activities – covers Chapter 4, 5, & 6 (120 min)
     Discuss the 7 Java control Structures. Start with the
      sequence structure. (30 min)
     Discuss the three selection structures – single selection = if;
      double selection = if/else; multiple selection = switch. (30 min)
     Discuss the three repetition structures – while ; do/while; for.
      (30 min)
     Discuss data manipulation, validation and formatting. (30 min)
   Coding Exercises & break (90 min)
     Code Ex 1 – p 249 – # 5.2.8 (a & b)
     Code Ex 2 – p 323 – # 6.4.6
     Code Ex 3 – p 225 – # 4.5.13
Structured-Programming Summary

   All programs broken down into
     Sequence
     Selection
        if,   if/else, or switch
          • Any selection can be rewritten as an if statement
     Repetition
        while,   do/while, or for
          • Any repetition structure can be rewritten as a while
            statement
  Flow of Control
      the order in which program
       statements are executed




WHAT ARE THE POSSIBILITIES. . .
                 Flow of Control
   is Sequential unless a “control structure” is used to
    change that

   there are 2 general types of control structures that
    change a sequential flow:

       Selection (also called branching)

       Repetition (also called looping)
                 Java control structures
   Selection
            if
            if . . . else
            switch
   Repetition
            for loop
            while loop
            do . . . while loop
                Selection Statements
   if-then-else statement: implements a
    decision structure for two alternatives

    Syntax:

    if (condition)
      statement executed if condition is true;
    else
      statement executed if condition is false;
The if-then-else Statement
   if-then-else performs instructions based on
    the result of a comparison
       Place statements on separate lines for readability


    Syntax:
if-then-else provides two-way
selection
 between executing one of 2 clauses (the if clause
   or the else clause)


         TRUE                    FALSE
                   condition



       if clause               else clause
If-Then-Else Syntax
      if ( Condition )
             StatementA
      else
             StatementB


NOTE: StatementA and StatementB each can be a
 single statement, a null statement, or a block.
Use of blocks is recommended
   if ( Condition ) {


                        “if clause”
   } else {


                        “else clause”
   }
The if-then-else Flowchart




The if-
then-else
flowchart.
            Example (Multiple Lines)

 int carDoors, driverAge ;
float premium, monthlyPayment ;
. . .
    if ( (carDoors == 4 ) && (driverAge > 24) )   {
            premium = 650.00 ;
           System.out.println(“ LOW RISK “ );
    } else {
            premium = 1200.00 ;
           System.out.println(“ HIGH RISK ”);
}


monthlyPayment = premium / 12.0 + 5.00 ;
What happens if you omit braces?

    if ( (carDoors == 4 ) && (driverAge > 24) )
            premium = 650.00 ;
           System.out.println(“ LOW RISK “) ;
   else
            premium = 1200.00 ;
           System.out.println(“ HIGH RISK ”) ;

   monthlyPayment = premium / 12.0 + 5.00 ;

 COMPILE ERROR OCCURS. The “if clause” is the single
   statement following the if.
Braces can only be omitted when
each clause is a single statement
 if ( lastInitial <= „K‟ )

           volume = 1;
 else
          volume = 2;

 System.out.println(“Look it up in volume # “
       + volume + “ of NYC phone book”);
               The Selection Condition

   The condition is evaluated to its boolean value:
     Can     ONLY use boolean values
   The else portion is optional
     It   is executed only if the condition is false
   The condition may be any valid Java
    expression that has a boolean value
                  Relational Expressions
   Relational expression: compares two
    operands or expressions using relational
    operators
     Evaluates   to true or false
            Logical Operators
   Logical operators
     AND   (&&): condition is true only if both
      expressions are true
     OR (||): condition is true if either one or both of
      the expressions is true
     NOT (!): changes an expression to its opposite
      state; true becomes false, false becomes true
             Logical Expressions
LOGICAL
EXPRESSION    MEANING    DESCRIPTION

!p             NOT p     ! p is false if p is true
                         ! p is true if p is false

p && q         p AND q   p && q is true if
                         both p and q are true.
                         It is false otherwise.

p || q         p OR q    p || q is true if either
                         p or q or both are true.
                         It is false otherwise.
    Caveats! (obscure)
   Comparing single and double precision values for
    equality (==) can lead to errors because values are
    stored in binary
   Reason is that numbers like 0.1 cannot be
    represented exactly in binary
   Thus, testing for exact equality of such numbers
    can fail
   Instead, test that the absolute value of the
    difference is within an acceptable range, epsilon (e)
   Example:
abs(operandOne – operandTwo)<0.000001
        What is the value?
int   age ;
boolean isSenior, hasFever ;
float temperature ;
age = 20;
temperature = 102.0 ;
isSenior = (age >= 55) ;                 // isSenior is false
hasFever = (temperature > 98.6) ;       // hasFever is true

       EXPRESSION                   VALUE
       isSenior && hasFever         ?

       isSenior || hasFever         ?
       ! isSenior                   ?
       ! hasFever                   ?
                   The value is…?
int age, height;

age = 25;
height = 70;
       EXPRESSION           VALUE
       !(age < 10)                  ?


       !(height > 60)               ?
    Write an expression for each
taxRate is over 25% and income is less than $20000


temperature is less than or equal to 75 or humidity is
  less than 70%


age is over 21 and age is less than 60


age is 21 or 22
 Some Answers

(taxRate > .25) && (income < 20000)

(temperature <= 75) || (humidity < .70)

(age > 21) && (age < 60)

(age == 21) || (age == 22)
WARNING about Expressions in Java
   “Boolean expression” means an expression whose
    value is true or false
   an expression is any valid combination of operators
    and operands
   each expression has a value
   this can lead to UNEXPECTED RESULTS
   construct your expressions CAREFULLY
   use of parentheses is encouraged
   otherwise, use precedence chart to determine order
If-Then-Else for a mail order

Assign value .25 to discountRate and assign
value 10.00 to shipCost if purchase is over
100.00

Otherwise, assign value .15 to discountRate
and assign value 5.00 to shipCost

Either way, calculate totalBill
These braces cannot be omitted
if ( purchase > 100.00 )
{
          discountRate = .25 ;
          shipCost = 10.00 ;
}
else
{
          discountRate = .15 ;
          shipCost = 5.00 ;
}

totalBill = purchase * (1.0 - discountRate) + shipCost ;
       The if-then Statement



   One-way selection: an if
    statement without the optional
    else portion
If-Then statement is a selection
 of whether or not to execute a statement (which can be a
    single statement or an entire block)
 One-way selection: an if statement without the optional
    else portion

             TRUE
                       expression



                              FALSE
         statement
If-Then Syntax

      if ( Expression )
            Statement



NOTE: Statement can be a single statement, a null
 statement, or a block.
                    Terminating your program
int number ;

String s1 = JOptionPane.showInputDialog(“Enter a non-zero number ”) ;
number = Integer.parseInt(s1);

if (number == 0 )
{
    JOptionPane.showMessageDialog(“Bad input. Program terminated ”);
     return 1 ;
}
                         // otherwise continue processing
What output? and Why?
 int age;

 age = 30;

 if ( age < 18 )

            JOptionPane.showMessageDialog( “Do you drive?”);
            JOptionPane.showMessageDialog(“Too young to vote”);
OPTIONAL: Both the if clause and the
else clause

of an if-then-else statement can
  contain any kind of statement,
  including another selection
  statement.
Multi-alternative Selection

           is also called multi-way branching,
           and
           can be accomplished by using
           NESTED if statements
           or
           using else-if‟s
 Multi-way Branching
 (if-else chaining)
  if ( Expression1 )
             Statement1
  else if ( Expression2 )
               Statement2
                     .
                     .
                     .
  else if ( ExpressionN )
               StatementN
  else
               Statement N+1
EXACTLY 1 of these statements will be executed.
               Nested if Statements
   if-then-else statements can contain any
    valid Java statement, including another if-
    then-else statement
   Nested if statement: an if-then-else
    statement completely contained within another
    if-then-else statement
   Use braces to block code, especially when the
    inner if statement does not have its own
    else statement
               Nested if Flowchart



if-then-
else
statement
nested in an
if-then.
 Nested if Statements
Each Expression is evaluated in sequence, until some
    Expression is found that is true.
Only the specific Statement following that particular true
    Expression is executed.
If no Expression is true, the Statement following the final else is
    executed.
Actually, the final else and final Statement are optional. If
    omitted, and no Expression is true, then no Statement is
    executed.
If any condition is true, the corresponding statement is
    executed and the chain terminates
Final else is only executed if no conditions were true; serves
    as a catch-all case
if-then-else chain provides one selection from many
    possible alternatives
                                                  AN EXAMPLE . . .
Multi-way Branching (if-else
chaining) example…
if ( creditsEarned >= 90 )
        System.out.println( “SENIOR STATUS “);
else if ( creditsEarned >= 60 )
        System.out.println(“JUNIOR STATUS “);
else if ( creditsEarned >= 30 )
     System.out.println(“SOPHOMORE
  STATUS “);
else
        System.out.println(“FRESHMAN STATUS
  “);
Nested if Statements Flowchart
         if-then-else statement
         nested in an else.




                         General form of an if-
                         then-else chain.
 Writing Nested if Statements
Display one word to describe the int value of a
  number as “Positive”, “Negative”, or “Zero”

Your city classifies a pollution index
   less than 35 as “Pleasant”,
   35 through 60 as “Unpleasant”,
    and above 60 as “Health Hazard.”
   Display the correct description of the
   pollution index value.
One Answer
 if (number >   0)

        System.out.println(“Positive”);

 else if (number < 0)

        System.out.println(“Negative”);

 else

        System.out.println(“Zero”);
          Other Answer
if ( index < 35 )

  System.out.println( “Pleasant”);

else if ( index <= 60 )

  System.out.println( “Unpleasant”);

else

  System.out.println( “Health Hazard”);
                  The switch Statement
   switch statement: provides for one selection from
    many alternatives
   switch keyword starts the statement; is followed by the
    expression to be evaluated
   case keyword identifies a value to be compared to the
    switch expression
   When a match is found, statements in this case block
    are executed
   All further cases after a match is found are executed
    unless a break statement is found
The switch Statement
(continued)
    default case is executed if no other case
     value matches were found
      default   case is optional
switch Syntax
while Repetition Structure
   Repetition control structure
     Action repeated while some condition remains true
     Psuedocode
         while there are more items on my shopping list
          Purchase next item and cross it off my list
       while loop repeated until condition becomes false

                                                This says: Execute
   Example
             int product = 2;
                                                  the next line over
             while ( product <= 1000 )            & over again until
                product = 2 * product;            product is > 1000

   Two varieties: event-controlled and count-
    controlled
 A While Statement
  SYNTAX


  while ( Expression )
  {     .
        .                // loop body
        .
  }




NOTE: Loop body can be a single statement, a null
 statement, or a block.
Repetition Structure Elements
   Repetition structure has three required elements:
     Statement to be repeated
     Condition to be evaluated
            Determines loop termination
       Initial value for the condition
   Repetition statements include
     while
     for
     do while
                  Basic Loop Structures
   The condition can be tested
     Atthe beginning: pretest or entrance-
      controlled loop
   The condition can be tested
     At   the end: posttest or exit-controlled loop
   Something in the loop body must cause the
    condition to change in order to avoid an infinite
    loop (one that never terminates)
Pre-test Symbology
   Pretest loop:
    condition is tested
    first; if false,
    statements in the
    loop body are never
    executed
     while  and for
      loops are pretest
      loops
Post-test Symbology

   Posttest loop: condition is
    tested after the loop body
    statements are executed;
    loop body always executes
    at least once
     do  while is a posttest
      loop
When the expression is tested and found to be false, the
 loop exits and control passes to the statement which
 follows the loop body.


WHILE LOOP

                                 TRUE      body
                  Expression
                                         statements

                 FALSE
    Number of Loop Iterations
   There are essentially two kinds of loop
    iterations:
   Fixed-count loop: loop is processed for a fixed
    number of repetitions
   Variable-condition loop: number of repetitions
    depends on the value of a variable
        Two Types of Loops
count controlled loops
  repeat a specified number of times


event-controlled loops
  some condition within the loop body changes and
  this causes the repeating to stop
Count-controlled loop contains

an initialization of the loop control
 variable

an expression to test for continuing the
loop

an update of the loop control variable
to be executed with each iteration of
the body
 Count-controlled Loop
int count ;

count = 4;                            // initialize loop variable

while (count > 0)                     // test expression
{
        System.out.println(count) ;   // repeated action

       count -- ;                     // update loop variable
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                          count

count = 4;

while (count > 0)
{
        System.out.println(count);   OUTPUT

       count -- ;
}
System.out.println(“Done!”);



                                              58
 Count-controlled Loop
int count ;                          count

count = 4;                             4
while (count > 0)
{
        System.out.println(count);   OUTPUT

       count -- ;
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                          count

count = 4;                             4
while (count > 0)     TRUE
{
        System.out.println(count);   OUTPUT

       count -- ;
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             4
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             3
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             3
while (count > 0)     TRUE
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             3
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             2
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             2
while (count > 0)     TRUE
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             2
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}                                    2
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             1
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}                                    2
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             1
while (count > 0)     TRUE
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}                                    2
System.out.println(“Done!”);
 Count-controlled Loop
int count ;                           count

count = 4;                             1
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}                                    2
System.out.println(“Done!”);         1
 Count-controlled Loop
int count ;                           count

count = 4;                             0
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}                                    2
System.out.println(“Done!”);         1
 Count-controlled Loop
int count ;                           count

count = 4;                             0
while (count > 0)     FALSE
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}                                    2
System.out.println(“Done!”);         1
 Count-controlled Loop
int count ;                           count

count = 4;                             0
while (count > 0)
{
        System.out.println(count);   OUTPUT
                                     4
       count -- ;                    3
}                                    2
System.out.println(“Done!”);         1
                                     Done!
                Event-controlled Loops
   Sentinel controlled
    keep processing data until a special value which is
      not a possible data value is entered to indicate
      that processing should stop

   End-of-file controlled
    keep processing data as long as there is more data
      in the file

   Flag controlled
    keep processing data until the value of a flag
      changes in the loop body
  Examples of Count-controlled and
  EOF Loops

Count controlled loop    Read exactly 100
                         blood pressures
                         from a file.


End-of-file controlled   Read all the blood
loop                     pressures from a
                         file no matter how
                         many are there.
   Examples of Sentinel and Flag
   Loops

Sentinel controlled   Read blood pressures
loop                  until a special value
                      (like -1) selected by you
                      is read.

Flag controlled       Read blood pressures
loop                  until a dangerously high
                      BP (200 or more) is read
                      then set flag to false.
                  Loops are often used to:
   count all data values

   count special data values

   sum data values

       keep track of previous and current values, etc.
Pattern of a Nested Loop
initialize outer loop
while ( outer loop condition )
{      ...

       initialize inner loop
       while ( inner loop condition )
       {
                inner loop processing and update
       } // end inner loop
       ...
} // end outer loop
                    for Loops
   for statement: a loop with a fixed count
    condition that handles alteration of the condition
    Syntax:
       for (initializing list; expression; altering list)
                 statement;
   Initializing list: sets the starting value of a
    counter
   Expression: contains the maximum or
    minimum value the counter can have;
    determines when the loop is finished
                 for Loops (continued)
   Altering list: provides the increment value that
    is added or subtracted from the counter in each
    iteration of the loop
     Ifaltering list is missing, the counter must be
      altered in the loop body
   If initializing list is missing, the counter initial
    value must be provided prior to entering the for
    loop
   Omitting the expression will result in an infinite
    loop
for Loop Symbology
for (int count = 1; count <= 10; count++) {
  System.out.println(“Count was: “ + count);
}




                for loop
                flowchart.
In-Class Exercise (follows)
         Based on following two
          programs…
    In-Class Exercise: count.java
// Program Count prompts for, reads, echo prints, and sums a
// fixed number of integer values. The sum is printed.

import javax.swing.*;

public class count {
  public static void main(String[] args){
    int counter;                  // loop-control variable
    int sum;                      // summing variable
    int dataValue;                // input value
    int LIMIT = 10;
    String s1;
    counter = 1;
    sum = 0;

        // Input and sum integer data values.
        while (counter <= LIMIT) {
            s1 = JOptionPane.showInputDialog(null, "Enter an integer value.");
            dataValue = Integer.parseInt(s1);
            sum = sum + dataValue;
            counter++;
        }

        JOptionPane.showMessageDialog(null, "Sum is " + sum);
        System.exit(0);
    }
}
    In-Class Exercise: count2.java
// Program Count2 prompts for, reads, and sums integer
// values until a negative number is read. The input
// values and the sum are printed.

import javax.swing.*;

public class count2 {
  public static void main(String[] args){
    int sum;                      // summing variable
    int dataValue;                // input value
    String s1;
    sum = 0;

        s1 = JOptionPane.showInputDialog(null, "To stop processing, enter a negative
        value.\n Enter an integer value");
        dataValue = Integer.parseInt(s1); //Read 1st data value to prepare for loop

        // Input and sum integer data values
        while (dataValue > 0) {
            sum = sum + dataValue;
            s1 = JOptionPane.showInputDialog(null, "Enter an integer value.");
            dataValue = Integer.parseInt(s1);
        }

        JOptionPane.showMessageDialog(null, "Sum is " + sum);
        System.exit(0);
    }
}
                    Exercises:
1. What is printed if the following data values are entered
   as prompted for count.java?
    8 5 3 -2 0 9 1 7 3 10


2. Is the loop in program count.java a count-controlled
   loop or an event-controlled loop? Explain.

3. What is printed if the following data values are entered
   one per line for count2.java?
    8 5 3 -2 0 9 1 7 3 10


4. Is the loop in program count2.java a count-controlled
   loop or an event-controlled loop? Explain.

5. SKIP: Change count.java so that the number of
   values to be read (LIMIT) is input from the keyboard
   rather than being set as a named constant. Please
   don’t forget to prompt for limit.

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:289
posted:11/18/2010
language:English
pages:85
Description: Flowchart for If Else Statement document sample