phone: 016-6933793
e-mail: darknessofsorrow@hotmail.com

Thursday, 25 October 2012

Flow of Control : Loops

Java Loop Statements: Outline
• The while statement
• The do-while statement
• The for Statement

Java Loop Statements
• A portion of a program that repeats a statement or a group of statements is called a loop.
• The statement or group of statements to be repeated is called the body of the loop.
• A loop could be used to compute grades for each student in a class.
• There must be a means of exiting the loop.

The while Statement
• Also called a while loop
• A while statement repeats while a controlling boolean expression remains true
• The loop body typically contains an action that ultimately causes the controlling boolean expression to become false.
• Syntax

while (Boolean_Expression)
{
       First_Statement
       Second_Statement
       …
}


Download, compile, and run WhileDemo


The do-while Statement
• Also called a do-while loop
• Similar to a while statement, except that the loop body is executed at least once
• Syntax

do
{
      Body_Statement(s)
}    while (Boolean_Expression);


• Don’t forget the semicolon!
• Figure 4.3 The action of the do-while loop in DoWhileDemo

• First, the loop body is executed.
• Then the boolean expression is checked.
-  As long as it is true, the loop is executed again.
-  If it is false, the loop is exited.
• Equivalent while statement

Statement(s)_S1
while (Boolean_Condition) {
     Statement(s)_S1
}


Using while to Read Input
• Download WhileWithScanner.java from the Examples link on the course webpage
• Compile and run a few times until you are comfortable with what the program does and
how it does it.

Infinite Loops
• A loop which repeats without ever ending is called an infinite loop.
• If the controlling boolean expression never becomes false, a while loop or a do-while loop will repeat without ending.
• Make sure a loop contains a statement which causes the boolean expression to become false eventually.

Nested Loops
• The body of a loop can contain any kind of statements, including another loop.

The for Statement
• A for statement executes the body of a loop a fixed number of times.
• Example

for (count = 1; count < 3; count++)
{
       System.out.println(count);
}


• Syntax

for (Initialization; Condition; Update)
Body_Statement


• Body_Statement can be either a simple statement or a compound statement in {}.
• Corresponding while statement

Initialization
while (Condition)
Body_Statement_Including_Update


• Download ForDemo

  


• Possible to declare variables within a for statement
int sum = 0;
for (int n = 1 ; n <= 10 ; n++)
{
      sum = sum + n;
}

• Note that variable n is local to the loop

Controlling Number of Loop Iterations
• If the number of iterations is known before the
loop starts, the loop is called a count-controlled
loop.
-  Use a for loop.
• Asking the user before each iteration if it is time
to end the loop is called the ask-before-iterating
technique.
- Appropriate for a small number of iterations
-  Use a while loop or a do-while loop.

The break Statement in Loops
• A break statement can be used to end a loop immediately.
• The break statement ends only the innermost loop or switch statement that contains the break statement.
• break statements make loops more difficult to understand.
• Use break statements sparingly (if ever).
• Note program fragment, ending a loop with a break statement, listing 4.8


The continue Statement in Loops
• A continue statement
- Ends current loop iteration
- Begins the next one
• Text recommends avoiding use
- Introduces unneeded complications

Tracing Variables
• Tracing variables means watching the variables change while the program is running.
 - Simply insert temporary output statements in your program to print of the values of variables of interest
- Or, learn to use the debugging facility that may be provided by your system.

Tracing Variables with Drjava
• Open WhileWithScanner.java
• Choose Debugger->Debug Mode
- A new panel is added with Stack and Thread tabs
• Right-click on the code sum += num; and choose Toggle Breakpoint
- That line now has a red background
• Click on the left-right arrows to the left of the Stack tab
 - A new panel is added with a Watches tab
• Type num into the Name field and hit return
• Type sum into the next Name field, then return
• Run the program and type some numbers when promted to do so
• The program will stop at the breakpoint and show the values of num and sum
• Click the Step Over button to move to the next statement
• Click the Resume button to move to the next breakpoint
• To exit the debugger and the program, click the Reset button located on the top panel

Loop Bugs
• Common loop bugs
- Unintended infinite loops
- Off-by-one errors
- Testing equality of floating-point numbers
• Subtle infinite loops
- The loop may terminate for some input values, but not for others.
- Example: you can’t get out of debt when the monthly penalty exceeds the monthly payment.

0 comments: