Chapter 5: Control Structures II - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Chapter 5: Control Structures II

Description:

System.out.println(fname ' ' lname ' ' score1 ' ' score2 ' ' score3 ' ' tot ' ' avg) ... int tot = 0; while (inFile.hasNext()) number=inFile.nextInt ... – PowerPoint PPT presentation

Number of Views:69
Avg rating:3.0/5.0
Slides: 44
Provided by: manasi61
Category:

less

Transcript and Presenter's Notes

Title: Chapter 5: Control Structures II


1
Chapter 5 Control Structures II
  • Java Programming
  • From Problem Analysis to Program Design,
  • Second Edition

2
Chapter Objectives
  • Learn about repetition (looping) control
    structures.
  • Explore how to construct and use
    count-controlled, sentinel-controlled,
    flag-controlled, and EOF-controlled repetition
    structures.
  • Examine break and continue statements.
  • Discover how to form and use nested control
    structures.

3
Why Is Repetition Needed?
  • There are many situations in which the same
    statements need to be executed several times.
  • Example
  • Formulas used to find average grades for students
    in a class.
  • Three looping structures
  • Whlie
  • For
  • Dowhile

4
The while Looping (Repetition) Structure
  • Syntax
  • while (expression)
  • statement
  • Expression is always true in an infinite loop.
  • Statements must change value of expression to
    false.

5
The while Looping (Repetition) Structure
  • Example 5-1
  • i 0 //Line 1
  • while (i lt 20) //Line 2
  • System.out.print(i " ") //Line 3
  • i i 5 //Line 4
  • System.out.println() //Line 5
  • Output
  • 0 5 10 15 20

6
The while Looping (Repetition) Structure
  • Typically, while loops are written in the
    following form
  • //initialize the loop control variable(s)
  • while (expression) //expression tests the LCV
  • .
  • .
  • .
  • //update the loop control variable(s)
  • .
  • .
  • .

7
  • public class loop1
  • public static void main(Stringargs)
  • int i // i is the loop control variable
    (LCV)
  • double j
  • i0 // the loop must be initialized
  • while (ilt25) // remember no after the
    expression
  • jMath.pow(i,3) // to raise i to the power of 3
  • System.out.println(i","j)
  • ii1 // if this statement is omitted, we
    have an infinite loop

8
Counter-Controlled while Loop
  • Used when exact number of data or entry pieces is
    known.
  • General form
  • int N //value input by user or specified
  • //in program
  • int counter 0
  • while (counter lt N)
  • .
  • .
  • .
  • counter
  • .
  • .
  • .

9
  • import java.util.
  • import java.io.
  • public class loop2
  • static Scanner console new Scanner(System.in)
  • public static void main(Stringargs)
  • throws FileNotFoundException
  • Scanner inFile new Scanner(new
    FileReader("loop.txt"))
  • int n
  • System.out.println("Please enter number of
    students in the class")
  • nconsole.nextInt()
  • int counter
  • counter1
  • while (counterltn)

10
  • String fname
  • String lname
  • int score1,score2,score3
  • int tot
  • double avg
  • fnameinFile.next()
  • lnameinFile.next()
  • score1inFile.nextInt()
  • score2inFile.nextInt()
  • score3inFile.nextInt()
  • tot score1score2score3
  • avgtot/3
  • System.out.println(fname " " lname " "
    score1" " score2" " score3" " tot" "
    avg)
  • counter
  • inFile.close()

11
Sentinel-Controlled while Loop
  • Used when exact number of entry pieces is
    unknown, but last entry (special/sentinel value)
    is known.
  • General form
  • Input the first data item into variable
  • while (variable ! sentinel)
  • .
  • .
  • .
  • input a data item into variable
  • .
  • .
  • .

12
  • import java.util.
  • import java.io.
  • public class loop2sentinel
  • static Scanner console new Scanner(System.in)
  • static final int SENTINEL-999
  • public static void main(Stringargs)
  • throws FileNotFoundException
  • Scanner inFile new Scanner(new
    FileReader("sentinel.txt"))
  • int number, tot, count1
  • tot0
  • count10
  • numberinFile.nextInt()
  • while (number ! SENTINEL)
  • tot tot number
  • numberinFile.nextInt()
  • System.out.println(count1 " " number)

13
Flag-Controlled while Loop
  • Boolean value used to control loop.
  • General form
  • boolean found false
  • while (!found)
  • .
  • .
  • .
  • if (expression)
  • found true
  • .
  • .
  • .

14
  • import java.util.
  • import java.io.
  • public class loopflag
  • static Scanner console new Scanner(System.in)
  • public static void main(Stringargs)
  • throws FileNotFoundException
  • Scanner inFile new Scanner(new
    FileReader("loopflag.txt"))
  • int number, tot
  • tot0
  • boolean found
  • foundfalse
  • numberinFile.nextInt()
  • while (!found)
  • if (numberlt0)
  • System.out.println("Wehave encountered a
    negative number")

15
EOF(End of File)-Controlled while Loop
  • Used when input is from files.
  • Sentinel value is not always appropriate.
  • In an EOF-controlled while loop that uses the
    Scanner object console to input data, console
    acts at the loop control variable.
  • The method hasNext, of the class Scanner, returns
    true if there is an input in the input stream
    otherwise, it returns false.
  • The expression console.hasNext() acts as the loop
    condition.
  • Expressions such as console.nextInt() update the
    value of the loop condition.

16
EOF-Controlled while Loop
  • A general form of the EOF-controlled while loop
    that uses the Scanner object console to input
    data is
  • while (console.hasNext())
  • //Get the next input and store in an
  • //appropriate variable
  • //Process data

17
EOF-Controlled while Loop
  • Suppose that inFile is a Scanner object
    initialized to the input file. In this case, the
    EOF-controlled while loop takes the following
    form
  • while (inFile.hasNext())
  • //Get the next input and store in an
  • //appropriate variable
  • //Process data

18
  • import java.util.
  • import java.io.
  • public class loopeof
  • static Scanner console new Scanner(System.in)
  • public static void main(Stringargs)
  • throws FileNotFoundException
  • Scanner inMike new Scanner(new
    FileReader("loopeof.txt"))
  • int number
  • int tot 0
  • while (inMike.hasNext())
  • numberinMike.nextInt()
  • tot tot number
  • System.out.println(number)
  • System.out.println("Total" " " tot)
  • inMike.close()

19
Programming Example Checking Account Balance
  • Input file Customers account number, account
    balance at beginning of month, transaction type
    (withdrawal, deposit, interest), transaction
    amount.
  • Output Account number, beginning balance, ending
    balance, total interest paid, total amount
    deposited, number of deposits, total amount
    withdrawn, number of withdrawals.

20
Programming Example Checking Account Balance
  • Solution
  • Read data.
  • EOF-controlled loop.
  • switch structure of transaction types.
  • Determine action (add to balance or subtract from
    balance depending on transaction type).

21
Programming Example Fibonacci Number
  • Fibonacci formula for any Fibonacci sequence
  • an an-1 an-2
  • Input First two Fibonacci numbers in sequence,
    position in sequence of desired Fibonacci number
    (n).
  • int previous1 Fibonacci number 1
  • int previous2 Fibonacci number 2
  • int nthFibonacci Position of nth Fibonacci
    number
  • Output nth Fibonacci number.

22
Programming Example Fibonacci Number (Solution)
  • if (nthFibonacci 1)
  • current previous1
  • else if (nthFibonacci 2)
  • current previous2
  • else
  • counter 3
  • while (counter lt nthFibonacci)
  • current previous2 previous1
  • previous1 previous2
  • previous2 current
  • counter
  • Final result found in last value of current.

23
The for Looping (Repetition) Structure
  • Specialized form of while loop.
  • Simplifies the writing of count-controlled loops.
  • Called a counted or indexed for loop
  • Syntax
  • for (initial statement loop condition
  • update statement)
  • statement

24
The for Looping (Repetition) Structure
  • Execution
  • Initial statement executes (once).
  • Loop condition is evaluated.
  • If loop condition evaluates to true, execute for
    loop statement and execute update statement.
  • Repeat until loop condition is false.

25
The for Looping (Repetition) Structure
  • Example 5-8
  • The following for loop prints the first 10
    nonnegative integers
  • for (i 0 i lt 10 i)
  • System.out.print(i " ")
  • System.out.println()

26
The for Looping (Repetition) Structure
  • Example 5-9
  • The following for loop outputs the word Hello and
    a star (on separate lines) five times
  • for (i 1 i lt 5 i)
  • System.out.println("Hello")
  • System.out.println("")
  • 2. The following for loop outputs the word Hello
    five times and the star only once
  • for (i 1 i lt 5 i)
  • System.out.println("Hello")
  • System.out.println("")

27
The for Looping (Repetition) Structure
  • Does not execute if initial condition is false.
  • Update expression changes value of loop control
    variable, eventually making it false.
  • If loop condition is always true, result is an
    infinite loop.
  • Infinite loop can be specified by omitting all
    three control statements.
  • e.g. for ( )
  • System.out.println (Hello World) //
    prints this line infinitely
  • If loop condition is omitted, it is assumed to be
    true.
  • for statement ending in semicolon is empty ie
    has empty action.
  • We can also count backwards using a for loop

28
  • public class forloop
  • public static void main(Stringargs)
  • int x
  • for(x0 xlt10 x)
  • System.out.println(x" ")
  • // the initial statement x0 initializes the
    variable x, Next the loop condition
  • // ilt10 is evaluated. Because ilt10 is true, the
    print statement executes and
  • // outputs 0. The update statement x then
    executes, which sets the value of x to 1.
  • // Again the loop condition is evaluated, which
    is still true, and so on

29
The dowhile Loop (Repetition) Structure
  • Syntax
  • do
  • statement
  • while (expression)
  • Statements are executed first and then expression
    is evaluated.
  • Statements are executed at least once and then
    continued if expression is true.
  • Could be simple or compound (enclosed in curly
    braces)

30
dowhile Loop (Post-Test Loop)
31
Dowhile VS for and while loops
  • Do...while always activates, for and while may
    never activate
  • In Do.. While loop condition is evaluated after
    execution of the loop (post- test loop), while in
    for and while, the loop condition is evaluated
    before the execution (pre-test loop)
  • Do while does not have an empty condition. For
    or while can have an empty condition

32
  • public class dowhile
  • public static void main(String args)
  • int i
  • i1
  • do
  • System.out.println(i "," 3i)
  • ii2
  • while(ilt40) // note the semicolon after the
    while statement

33
  • // do...while and while loops compared
  • i11
  • while(ilt10)
  • System.out.println()
  • System.out.println(i"," ii)
  • ii2
  • //This produces nothing because the loop
    condition is false (gt10) from the beginning.
  • i11
  • do
  • System.out.println()
  • System.out.println(i"," ii)
  • ii2
  • while(ilt10)
  • // Here the loop outputs the number 11, and also
    changes the value of i to 112 before
  • // evaluating the loop condition

34
break Statements
  • Used to exit early from a loop.
  • Used to skip remainder of switch structure.
  • Can be placed within if statement of a loop.
  • If condition is met, loop is exited immediately.
  • After the break statement executes, the program
    continues to execute starting from the first
    statement after the structure

35
  • import java.util.
  • import java.io.
  • public class loopbreak
  • static Scanner console new Scanner(System.in)
  • public static void main(Stringargs)
  • throws FileNotFoundException
  • Scanner inFile new Scanner(new
    FileReader("loopeof.txt"))
  • int number
  • int tot 0

36
  • while (inFile.hasNext())
  • numberinFile.nextInt()
  • if(numberlt0)
  • System.out.println("A Negative number has been
    encountered")
  • break
  • tot tot number
  • System.out.println(number)
  • System.out.println("Total" " " tot)
  • inFile.close()

37
continue Statements
  • Used in while, for, and do...while structures.
  • When executed in a loop, the remaining statements
    in the loop are skipped proceeds with the next
    iteration of the loop.
  • When executed in a while/dowhile structure,
    expression is evaluated immediately after
    continue statement.
  • In a for structure, the update statement is
    executed after the continue statement the loop
    condition then executes.

38
  • import java.util.
  • import java.io.
  • public class loopcontinue
  • static Scanner console new Scanner(System.in)
  • public static void main(Stringargs)
  • throws FileNotFoundException
  • Scanner inFile new Scanner(new
    FileReader("loopeof.txt"))
  • int number
  • int tot 0
  • while (inFile.hasNext())
  • numberinFile.nextInt()
  • if(numberlt0)
  • System.out.println("A Negative number has been
    encountered")
  • continue

39
Nested Control Structures
  • Provides new power, subtlety, and complexity.
  • if, ifelse, and switch structures can be placed
    within while loops.
  • for loops can be found within other for loops.

40
Nested Control Structures (Example)
  • for (int i 1 i lt 5 i)
  • for (int j 1 j lt i j)
  • System.out.print(" ")
  • System.out.println()
  • Output

41
  • import java.util.
  • import java.io.
  • public class nestedloop
  • static Scanner console new Scanner(System.in)
  • public static void main(Stringargs)
  • throws FileNotFoundException
  • Scanner inFile new Scanner(new FileReader
    ("nestedloop.dat"))
  • char grade
  • int score
  • int count 0
  • String stdid
  • stdid""

42
  • System.out.println("STUDENT-ID" " " "SCORE""
    " "GRADE")
  • while(!stdid.equals("XXXX"))
  • count
  • stdidinFile.next()
  • scoreinFile.nextInt()
  • if(scoregt90)
  • grade'A'
  • else if(scoregt80)
  • grade'B'
  • else if(scoregt70)
  • grade'C'
  • else if(scoregt60)
  • grade'D'-
  • else grade'F'
  • System.out.println(stdid" "score"
    " grade)
  • // endwhile
  • System.out.println("\nStudents in
    class"""count)
  • inFile.close()

43
Chapter Summary
  • Looping mechanisms
  • Counter-controlled while loop
  • Sentinel-controlled while loop
  • Flag-controlled while loop
  • EOF-controlled while loop
  • for loop
  • dowhile loop
  • break statements
  • continue statements
  • Nested control structures
Write a Comment
User Comments (0)
About PowerShow.com