Saturday 3 August 2013

17:while, do-while, for

Learning Objectives
After completing this session, you will be able to:
‰  Use repetition control structures (while, do-while, for), which allow executing specific
sections of code a number of times
‰  Use branching statements (break, continue, return), which allows redirection of
program flow
Repetition Control Structures
Repetition control structures are Java statements that allows you to execute specific blocks of
code a number of times.
Types of repetition control structures are:
‰  while-loop
‰  do-while loop
‰  for-loop
while-loop
while loop is a statement or block of statements that is repeated as long as some condition is
satisfied.
while loop has the following form:
while( boolean_expression ){
statement1;
statement2;
. . .
}
The statements inside the while loop are executed as long as the boolean_expression evaluates to
true.
Examples of while-loop
Example 1:
int x = 0;
while (x<10) {
System.out.println(x);
x++;
}
Example 2:
//infinite loop
while(true)
System.out.println(“hello”);
Example 3:
//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);
do-while-loop
do-while loop:
‰  Similar to the while-loop
‰  Statements inside a do-while loop are executed several times as long as the condition
is satisfied
‰  The main difference between a while and do-while loop is that the statements inside a
do-while loop are executed at least once
‰  do-while loop has the following form:
do{
statement1;
statement2;
. . .
}while( boolean_expression );
Examples of do-while-loop
Example 1:
int x = 0;
do {
System.out.println(x);
x++;
} while (x<10);
Example 2:
//infinite loop
do {
System.out.println(“hello”);
while(true);
Example 3:
//one loop
// statement is not executed only once
do {
System.out.println(“hello”);
} while (false);
Coding Guidelines
Common programming mistakes when using the do-whileloop is forgetting to write the semi-colon
after the while expression.
do{
...
}while(boolean_expression)//WRONG->forgot semicolon;
Just like in while loops, make sure that yourdo-while loops will terminate at some point.
for-loop
for loop allows execution of the same code a number of times.
for loop has the following form:
for(InitializationExpression;LoopCondition;StepExpression)
{
statement1;
statement2;
. . .
}
Where:
‰  InitializationExpression initializes the loop variable.
‰  LoopCondition compares the loop variable to some limit value.
‰  StepExpression updates the loop variable.
Example of for-loop
int i;
for( i = 0; i < 10; i++ ){
System.out.println(i);
}
The preceding code shown is equivalent to the following while loop:
int i = 0;
while( i < 10 ){
System.out.println(i);
i++;
}
Branching Statements
Branching statements allows you to redirect the flow of program execution.
Java offers three branching statements:
‰  break
‰  continue
‰  return
Unlabelled Break Statement
Unlabelled break:
‰  Terminates the enclosing switch statement, and flow of control transfers to the
statement immediately following the switch
‰  This can also be used to terminate a for, while, or do-while loop
Example of Unlabelled Break Statement
String
names[]={"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"};
String searchName = "Yza";
boolean foundName = false;
for( int i=0; i< names.length; i++ ){
if( names[i].equals( searchName )){
foundName = true;
break;
}
}
if( foundName ) System.out.println( searchName + " found!" );
else System.out.println( searchName + " not found." );
Labeled Break Statement
Labeled break statement:
‰  This terminates an outer statement, which is identified by the label specified in the
break statement
‰  The flow of control transfers to the statement immediately following the labeled
(terminated) statement.
‰  The sample program in the following slide searches for a value in a two dimensional
array. Two nested for loops traverse the array. When the value is found, a labeled
break terminates the statement labeled search, which is the outer for loop.

Example of Labeled Break Statement
int[][] numbers = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}};
int searchNum = 5;
boolean foundNum = false;
searchLabel:
for( int i=0; i<numbers.length; i++ ){
for( int j=0; j<numbers[i].length; j++ ){
if( searchNum == numbers[i][j] ){
foundNum = true;
break searchLabel;
}
}
}
if( foundNum ) System.out.println(searchNum + " found!" );
else System.out.println(searchNum + " not found!");
Unlabelled Continue Statement
Unlabelled continue statement skips to the end ofthe body of the innermost loop and evaluates
the boolean expression that controls the loop, basically skipping the remainder of this iteration of
the loop.
Example of Unlabelled Continue Statement
String names[] = {"Beah", "Bianca", "Lance", "Beah"};
int count = 0;
for( int i=0; i<names.length; i++ ){
if( !names[i].equals("Beah") ){
continue; //skip next statement
}
count++;
}
System.out.println("There are "+count+" Beahs in the list");
Labeled Continue Statement
Labeled continue statement skips the current iteration of an outer loop marked with the given label.
Example of Labeled Continue Statement
outerLoop:
for( int i=0; i<5; i++ ){
for( int j=0; j<5; j++ ){
System.out.println("Inside for(j) loop"); //message1

if( j == 2 ) continue outerLoop;
}
System.out.println("Inside for(i) loop"); //message2
}
In this example, message 2 never gets printed since you have the statement continue outerLoop,
which skips the iteration.
Return Statement
Return statement:
Applied to exit from the current method
Flow of control returns to the statement that follows the original method call
To return a value:
Simply put the value (or an expression that calculates the value) after the return keyword. For
example:
return ++count;
or
return "Hello";
The data type of the value returned by return must match the type of the declared return value of
the method. When a method is declared void, use the form of return that does not return a value.
For example:
return;
Try It Out
Problem Statement:
Write a program that illustrates the use of for loop.
Code:
class ForLoop {
public static void main(String[] args) {
int i, j;
for (i = 0, j = 0; i + j < 20; ++i, j += i) {
System.out.println(i + j);
}
}
}
How It Works:
‰  A little-known fact about the for statement is that commas can be used to separate
multiple statements in the initialization and iteration part of the statement.
‰  The only catch is, if you apply a comma separator in the initialization block, then you
cannot declare variables within the initialization block.
‰  For example, the following for statement results in a compilation error:
for(int i=0,int j=0; i+j < 20; ++i, j += i) {
System.out.println(i+j);
}
‰  When you run ForLoop.java program, it produces the following output:
0
2
5
9
14
Tips and Tricks:
Provide few important tips on branching statements.
Solution:
‰  break statement can be used with any kind ofloop or a switch statement or just a
labeled block.
‰  continue statement can be used with only a loop. (any kind of loop).
‰  Loops can have labels. You can use break and continue statements to branch out of
multiple levels of nested loops using labels.
‰  Names of the labels follow the same rules as the name of the variables (Identifiers).
‰  Labels can have the same name, as long as they do not enclose one another.
‰  There is no restriction against applying the same identifier as a label and as the name
of a package, class, interface, method, field, parameter, or local variable.
Summary
The types of Repetition Control Structures are:
‰  while
‰  do-while
‰  for
‰  The types of Branching Statements are:
‰  break
‰  continue
‰  return
Test Your Understanding
1.Which of the following is true in the case of ‘while’ structure?
a)Condition is checked atthe bottom of the loop
b)Condition is checked at the top of the loop
c)Condition is checked at the top and bottom of the loop
d)No condition is checked


No comments:

Post a Comment