Loops and Other Flow of Control Structures


Loops and Other Flow of Control Structures

A common programming need is to perform a given operation or computation over and over, either a set number of times or until a certain condition is met. You may also want to execute different sections of code depending on the evaluation of a condition. Java provides a wide variety of loops and flow of control structures to satisfy these programming requirements. This section will describe and demonstrate these structures.

if ”else Statements

The if-else statement is a basic conditional branch statement. It allows you to selectively execute blocks of code according to whether a condition is satisfied. More than one condition can be tested and a default block of code can be provided if none of the conditions are met. The general syntax of the if-else statement is as follows ”

 if (condition1) {    //  execute this code } else if (condition2) {    //  execute some other code } else {    //  default code } 

The conditions are expressions that evaluate to true or false values. The first condition to be tested is placed inside parentheses after the if keyword. You can nest if-else statements to test more than one condition. The block of code after the final else statement is a default block of code that is executed if none of the conditions are met. The else block is optional.

The conditions are evaluated in sequential order. If a condition is met, the block of code following the condition is executed and the if-else structure is exited. You can have compound conditions; for example, if (a == 2 && b < 0) . If only one executable statement follows the condition, the braces can be omitted, but this practice can be dangerous. If additional code is added at a later time you will have to remember to put the braces in. The safe way is to always use braces.

Example: Using if-else Statements

This is a typical example of using an if-else statement to evaluate an expression according to the value of a certain variable. In this case, we are computing a temperature-dependent property named gamma . Below a temperature of 500 K (Kelvin), gamma is a constant. Above 500 K, gamma is a function of temperature. Let us assume that the database for gamma only goes up to 2000 K. At temperatures above 2000 K, we can either extrapolate the value of gamma or set it to a fixed value.

A nested if-else statement is used to determine which expression for gamma should be used based on an input temperature. Another if-else statement decides what to do if the temperature exceeds the database range. Braces were used after every if and else statement. In some cases the braces aren't strictly necessary, but it is a safe way to program.

 public class IfDemo {   public static void main(String args[]) {     double temperature = 2340.0;     double gamma;     boolean extrapolate = false;     if (temperature < 500.0) {        gamma = 17.0;     } else if (temperature < 2000.0) {        gamma = 2.5 + 0.0295*temperature;     } else {        System.out.println("temperature exceeds database range");        if (extrapolate) {           gamma = 2.5 + 0.0295*temperature;        } else {           gamma = 61.5;        }     }     System.out.println("gamma is " + gamma);   } } 

Output ”

 temperature exceeds database range gamma is 61.5 

while Loops

A while loop is a construct that executes a block of code as long as a condition is met. The condition can either be the value of a boolean variable or a boolean expression. The general syntax of a while loop is as follows ”

 while (condition) {    //  code to execute } 

The block of code after the condition will only execute if the condition is true. If the condition is never true, the block of code will never execute. Conversely, the syntax while (true) will create an infinite loop. Unlike C, the integers 1 and 0 cannot be used to represent true and false. You cannot, for instance, use the following syntax in a Java program ”

 while (1) {    //  code to execute } 

You could, however, use the following syntax, which, in this case, would create an infinite loop ”

 while (true) {    //  code to execute } 
Example: Using while Loops

Look at the "Using Relational Operators" example earlier in this chapter where a while loop is used to test for convergence.

do-while Loops

The do-while loop is similar to the while loop in that it will execute a block of code until a condition is met. With a do-while loop, the block of code is executed before the condition is evaluated. Therefore, the block of code is guaranteed to execute at least once. The general syntax for a do-while loop is as follows ”

 do {    //  code to execute } while (boolean expression); 

A do-while loop is useful for mathematical iterations and for creating console menus that redisplay themselves until the user types a certain keystroke.

Example: Using do-while Loops

In this example, a do-while loop is used to solve a fourth-order equation. The equation is solved using a Newton-Raphson iteration process. An initial guess is made of the dependent variable. An update to the dependent variable is found by computing the ratio of the current value of the function divided by the slope of the function. The iteration is placed inside a do-while loop and proceeds until the desired level of convergence is achieved. A do-while loop is used instead of a while loop because the evaluation of deltaT has to be performed at least once to compare it with the convergence criteria.

 public class DoWhileDemo {   public static void main(String args[]) {     double T = 0.0, deltaT, f, dfdT, tolerance = 0.001;     int iteration = 0;     //  The 4th-order equation T^4  2.5T = 1.5 is     //  solved using a do-while loop     do {          f = Math.pow(T,4.0) - 2.5*T - 1.5;          dfdT = 4.0*Math.pow(T,3.0) - 2.5;          deltaT = -f/dfdT;          T += deltaT;          ++iteration;     } while (Math.abs(deltaT) > tolerance);     f = Math.pow(T,4.0) - 2.5*T;     System.out.println("convergence achieved in " +                         iteration+" steps");     System.out.println("T = " + T + "  f = " + f);   } } 

Output ”

 convergence achieved in 3 steps T = -0.56051718541   f = 1.5000173128 

for Loops

The for loop is similar to the while loop in that it can be used to execute a block of code a number of times. A for loop is commonly used to iterate through the elements of an array. The general syntax of the for loop is as follows ”

 for (initialization; expression; update) {    // code to execute } 

There are three parts to the syntax following the for keyword. There is an initialization statement that usually initializes the value of a loop control variable. This variable is typically part of the condition to be evaluated. The expression is a boolean that is evaluated every iteration. As long as the expression is true, the subsequent block of code is executed. The update part of the for loop usually increments or decrements the control variable. The update gets invoked after each iteration of the loop.

The initialization , expression , and update parts of the for loop are separated by semicolons. More than one statement can be placed inside the initialization and update sections, in which case commas separate the statements. You can nest for loops. Any or all of the three parts of the for loop can be omitted. For example, the following syntax creates an infinite loop ”

 for (;;) { } 
Example: Using for Loops

A typical use of for loops in scientific or engineering programming is to cycle through the elements of an array. In this example, elements of a 2-D array are assigned values using a pair of for loops, one for the rows of the array and one for the columns . The loop control variables ( i and j ) are defined in, and are local to, their respective for loops. More information about arrays can be found in Chapter 13.

 public class ForDemo {   public static void main(String args[]) {      int numSpecies = 3;      double moleFr[] = { 0.1, 0.4, 0.5 };      double dataArray[][] =               new double[numSpecies][numSpecies];      for (int i=0; i<numSpecies; ++i) {        for (int j=0; j<numSpecies; ++j) {          dataArray[i][j] = moleFr[i]*moleFr[j];          System.out.println("dataArray[" + i + "][" + j +                       "] = " + dataArray[i][j]);        }      }   } } 

Output ”

 dataArray[0][0] = 0.01 dataArray[0][1] = 0.04 dataArray[0][2] = 0.05 dataArray[1][0] = 0.04 dataArray[1][1] = 0.16 dataArray[1][2] = 0.2 dataArray[2][0] = 0.05 dataArray[2][1] = 0.2 dataArray[2][2] = 0.25 

switch Statements

A switch statement provides an alternative way to conditionally execute blocks of code as compared to an if-else statement. The result of an expression is compared against a number of values defined by case labels. If a match is found, the code following the case label is executed. An optional default label can be included that defines code to be executed if none of the case label values match the expression. The general syntax of a switch statement is ”

 switch (expression) {    case value1:        // execute some code       break;    case value2:       // execute this code       break;    default:      //  execute default code } 

The expression following the switch keyword must evaluate to a byte , short , int , or char . The values in the case labels must either be a constant expression or a static final variable. The case labels are terminated with colons rather than semicolons. You can nest switch statements.

The break statement causes the execution to exit the switch statement. The break statements are optional, but most of the time you will want to use them. If a break statement is omitted, the execution will continue to the next case label. This can sometimes be useful if you want to execute the same code after more than one case .

One difference between switch statements and if-else statements is that a case label only compares a single value. You can't build intricate boolean expressions ( if a << b && b==4 ) into a switch statement.

Example: Using a switch Statement

In this example, a switch statement is used to allow the selection and execution of different physical models, depending on the value of a variable. Blottner, Gupta, and Sutherland are some of the models used for computing transport property coefficients. The value of the model variable is compared against the value of three case statements. The values that model is compared against are defined as static final variables. This makes the code easier to read and understand than if numbers were used in the case statements.

If a match is found, the code following the case statement is executed. In this simple example the name of the model selected is printed. In a real-life application, the transport property coefficients would be computed according to the selected model. The break statements exit the switch structure once the appropriate code is executed.

The Sutherland model is the default. There is no break statement after the case SUTHERLAND: syntax. If the value of model is 0 the code flows through to the default statement that indicates the Sutherland model was selected. Any model value other than 0, 1, or 2 will go to the default label as well.

 public class SwitchDemo {   static final int SUTHERLAND = 0;   static final int BLOTTNER = 1;   static final int GUPTA = 2;   public static void main(String args[]) {     int model = 0;     switch (model) {       case BLOTTNER:         System.out.println("Blottner selected");         break;       case GUPTA:         System.out.println("Gupta selected");         break;       case SUTHERLAND:       default:         System.out.println("Sutherland selected");     }   } } 

Output ”

 Sutherland selected 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net