Thursday, January 13, 2011

Learning Objects for Control Structures in Java

Summary: These learning objects are for control structures in Java. Control structures change the dynamic flow of a program and include if, loop, and switch statements.







Learning Objects for Control Statements

Concept Normally, statements in Java are executed sequentially in the order written in the source code. Control statements are used to modify the order of execution of statements. Most control statements are conditional; that is, the next statement to be executed depends on the result of evaluating an expression, usually, an expression that returns a boolean value of true or false.
These source code of these learning objects can be found in control.zip.
TABLE 1
LOTopicJava Files (.java)Prerequisites
"If-statements"If-statementsControl01 
"Conditional expressions"Conditional expressionsControl021
"While loops"While loopsControl03 
"Do-while loops"Do-while loopsControl04 
"Break statements"Break statementsControl053
"Counting with for statements"Counting with for statementsControl06 
"General for statements"General for statementsControl076
"Continue statements"Continue statementsControl086
"Switch statements"Switch statementsControl09 

If-statements

Concept The execution of an if-statement starts with the evaluation of its boolean-valued expression. If the result is true, the statement written after the closing parenthesis of the expression is executed; if the result is false, the statement written after the else is executed. These statements can be single statements or blocks of statements. In particular, the statements can themselves be if-statements (nested if-statements), in which case the inner statement is executed the same way.
Program: Control01.java
// Learning Object Control01
//    if statements
public class Control01 {
    public static void main(/*String[] args*/) {
        int year = 2000;
        int month = 6;
        int days;
        if (month == 2)
            if (year % 4 == 0)
                days = 28;
            else
                days = 29;
        else if (month == 4 || month == 6 ||
                month == 9 || month == 11)
            days = 30;
        else
            days = 31;
        System.out.println(days);
    }
}
The program computes the number of days in a month taking leap years into account.
  • The variables are allocated and the first two, year and month, are given initial values.
  • The expression month == 2 evaluates to false, so the statement following the else is executed. Jeliot will display Choosing else-branch to emphasize this.
  • The inner statement is itself an if-statement. The expression is evaluated and its result is true. Note that once one of the terms of || (or) becomes true, there is no need to evaluate the others.
  • The assignment statement following the statement is executed. Jeliot will display Choosing then-branch. (The terminology then-branch orginates from programming languages that require the use of the keyword then between the expression and the statement.)
  • The value of days is printed.
Exercise Complete the program with the correct computation for leap years: a year divisible by 100 is not a leap year unless it is also divisible by 400.

Conditional expressions

Concept A conditional expression is a shorthand for an if-statement that assigns different values to one variable:
if (expression) var = value1; else var = value2;
This can be rewritten more concisely as:
var = (expression) ? value1 : value2;
The boolean-valued expression is evaluated: If the result is true, value1 is assigned to var; if not, value2 is assign to var.
Program: Control02.java
// Learning Object Control02
//    conditional expressions
public class Control02 {
    public static void main(/*String[] args*/) {
        int year = 2001;
        int month = 2;
        int days;
        if (month == 2)
            days = (year % 4 == 0) ? 28 : 29;
        else if (month == 4 || month == 6 ||
                month == 9 || month == 11)
            days = 30;
        else
            days = 31;
        System.out.println(days);
    }
}
The program computes the number of days in a month taking leap years into account.
  • The variables are allocated and the first two, year and month, are given initial values.
  • The expression month == 2 evaluates to true, so the statement following the expression is executed. Jeliot will display Choosing then-branch to emphasize this.
  • The inner statement is an assignment statement with a conditional expression. The expression is evaluated and its result is false, so the value after the colon is assigned to the variable. Jeliot will display Choosing else-branch.
  • The value of days is printed.
Exercise Complete the program with the correct computation for leap years: a year divisible by 100 is not a leap year unless it is divisible by 400.
Exercise Rewrite the entire if-statement as nested conditional expressions.

While loops

Concept A loop enables the execution of a statement (including a block of statements within braces) an arbitrary number of times. This statement is called the loop body. In a while loop, an expression is evaluated before each execution of the loop body, and loop body is executed if and only if the expression evaluates to true.
Program: Control03.java
// Learning Object Control03
//    while loops
public class Control03 {
    static int LIMIT = 100;
    public static void main(/*String[] args*/) {
        int factorial = 1;
        int n = 1;
        while (factorial < LIMIT) {
            System.out.println(factorial);
            n++;
            factorial = factorial * n;
        }
    }
}
This program prints all factorials less than LIMIT = 100, namely, 1!=12!=23!=64!=24.
  • The static constant and the two variables are allocated and initialized.
  • Then, and each time the keyword while is reached, the expression is evaluated. If it is true, execution proceeds with the loop body, and Jeliot displays Entering the while loop the first time and Continuing the while loop on subsequent occasions.
  • The statements of the loop body are executed. They print the value of the current factorial, increment the counter and compute the new factorial; then, control returns to the while-expression.
  • If and when the expression evaluates to false, execution proceeds with the statement following the loop body. Jeliot displays Exiting the while loop.
Exercise According to a formula by Euler,
1
12
 +
1
22
 +
1
32
 +
1
42
 +=
π2
6
(1)
Write a program to compute the series until the difference between the two terms is less than 0.1.

Do-while loops

Concept A loop enables the execution of a statement (including a block of statements within braces) an arbitrary number of times. This statement is called the loop body. In a do-while loop, an expression is evaluated after each execution of the loop body, and the loop body continues to execute if and only if the expression evaluates to true.
The loop body of a do-while loop will execute at least one time. This type of statement is particularly appropriate for processing input, because you need to input data at least once before you can test it in an expression.
Program: Control04.java
// Learning Object Control04
//    do-while loops
public class Control04 {
    public static void main(/*String[] args*/) {
        int input;
        do {
             input = Input.nextInt();
        } while (input <= 0);
        System.out.println(input);
    }
}
The program reads interactive input until a positive number is entered.
  • The variable input is allocated but not initialized.
  • The loop body of the do-while loop is executed. Jeliot displays Entering the do-while loop.
  • A value is read interactively into the variable input. First, enter a negative integer.
  • The expression following the while is evaluated. Since it evaluates to true, the loop body is executed again. Jeliot displays Continuing the do-while loop.
  • Now enter a positive value into the variable input.
  • The expression following the while is evaluated. Since it evaluates to false, the execution of the do-while loop is completed. Jeliot displays Exiting the do-while loop.
Exercise Rewrite this program with a while loop. Compare it to the do-while loop.

Break statements

Concept The exit from a while loop occurs before the loop body and the exit from a do-while loop occurs after the loop body. The break statement can be used to exit from an arbitrary location or locations from within the loop body.
The break statement is useful when the expression that leads to exiting the loop cannot be evaluated until some statements from the loop body have been executed, and yet there remain statements to be executed after the expression is evaluated.
Program: Control05.java
// Learning Object Control05
//    break statements
public class Control05 {
    public static void main(/*String[] args*/) {
        int input;
        int sum = 0;
        while (true) {
            input = Input.nextInt();
            if (input < 0) break;
            sum = sum + input;
        }
        System.out.println(sum);
    }
}
The program sums a sequence of nonnegative integers read from the input and terminates when a negative value is read.
  • The two variables are allocated and sum is initialized with the value zero.
  • The while statement is executed with true as the loop expression. Of course, true will never evaluate to false, so the loop will never be exited at the while.
  • An integer value is read from the input. If it is negative the break statement is executed and Jeliot displays Exiting the while loop because of the break.
  • Otherwise, the following assignment statement is executed and Jeliot displays Continuing without branching.
  • After the assignment statement is executed, the loop starts again.
Exercise Write equivalent programs using a while loop and a do-while loop.

Counting with for statements

Concept Although all loop structures can be programmed as while loops, one special case is directly supported: writing a loop that executes a predetermined number of times. Thefor statement has three parts:
for (int i = 0; i < N; i++)
The first part declares a loop control variable and gives it an initial value. The second part contains the exit condition: the loop body will be executed as long as the expression evaluates to true. The third part describes how the value of the control variable is modified after executing the loop body. The syntax show is the conventional one for executing a loop N times.
Program: Control06.java
// Learning Object Control06
//    counting with for statements
public class Control06 {
    static final int N = 6;
    public static void main(/*String[] args*/) {
        int factorial = 1;
        for (int i = 0; i < N; i++)
            factorial = factorial * (i+1);
        System.out.println(factorial);
    }
}
This program computes the first six factorials in a for loop and the last value is printed.
  • The constant N and the variable factorial are allocated and initialized.
  • The control variable i is allocated and initialized.
  • The expression i < N is evaluated and evaluates to true. Jeliot displays Entering the for loop.
  • The loop body is executed.
  • The control variable is incremented as specified in the third part of the for statement.
  • The previous three steps are repeated until the expression evaluates to false; this causes the loop to be exited. Jeliot displays Continuing the for loop as long as the expression evaluates to true, and Exiting the for loop when it evaluates to false.
  • The final value of factorial is printed.
  • Important: when the loop is exited, the control variable is deallocated and no longer exists.
Exercise Rewrite the program using a while loop.

General for statements

Concept Arbitrary expressions can be given for the initial value of the for statement, the exit condition, and the modification of the control variable.
Program: Control07.java
// Learning Object Control07
//    General for statements
public class Control07 {
    static final int N = 100;
    public static void main(/*String[] args*/) {
        int sum = 0;
        for (int i = 0; i < Math.sqrt(N); i = i + 3)
            sum = sum + i;
        System.out.println(sum);
    }
}
This program computes the sum of multiples of three that are less than the square root of N.
  • The constant N and the variable sum are allocated and initialized.
  • The control variable i is allocated and initialized.
  • The expression i < Math.sqrt(N) is evaluated and evaluates to true. Jeliot displays Entering the for loop.
  • The loop body is executed.
  • The control variable is incremented by three as specified in the third part of the for statement.
  • The previous three steps are repeated until the expression evaluates to false; this causes the loop to be exited. Jeliot displays Continuing the for loop as long as the expression evaluates to true, and Exiting the for loop when it evaluates to false.
  • The final value of sum is printed.
  • Important: when the loop is exited, the control variable is deallocated and no longer exists.
Exercise Is for (;;;) legal? If so, what does it mean?
Exercise Modify the program so that the square root is computed only once.

Continue statements

Concept The break statement is used to exit a loop from an arbitrary location in its body; the continue statement is used to skip the rest of a loop body and return to evaluate the condition for continuing the loop.
Program: Control08.java
// Learning Object Control08
//    continue statements
public class Control08 {
    static final int N = 10;
    public static void main(/*String[] args*/) {
        int sum = 0;
        for (int i = 0; i < N; i++) {
            if (i % 2 == 0) {
                if (i % 3 == 0)
                    continue;
                else
                    sum = sum + i;
            }
            else if (i % 3 == 0)
                sum = sum + i;
            else
                continue;
        }
        System.out.println(sum);
    }
}
This program sums all the positive integers less than N that are divisible by 2 or 3 but not by both. For N=10, the result is 2+3+4+8+9=26.
  • The constant N and the variable sum are allocated and initialized.
  • The for loop is standard and is executed for the values 0 through N1.
  • If i is divisible by 2 and also by 3 (for example, 6), the continue statement is executed and the variable sum is not modified.
  • If i is divisible neither by 2 nor by 3 (for example, 5), the continue statement is executed and the variable sum is not modified.
  • In all other cases, the value of i is added to sum.
  • The final value of sum is printed.
Exercise Modify the program so that it explicitly checks for divisibility by 6, instead of checking for divisibility by 2 and 3 in separate statements.
Exercise Modify the program so that continue is not used.

Switch statements

Concept A switch statement is a generalization of an if statement. Instead of selecting between two alternatives depending on the value of a boolean-valued expression, an integer-valued expression is used and there can be multiple alternatives introduced by the keyword case. Since there are a very large number of integer values, an alternative labeleddefault is executed when the value in the expression is not explicitly listed in one of the alternatives.
Important: In an if-statement, the end of the statement (or block of statements) of the first alternative causes a transfer of control to the end of the if statement, skipping over the statement (or block of statements) in the second (else) alternative. This does not happen in a switch: control “drops through” from the end of one alternative to the beginning of the next alternative. A break statement must be used to transfer control from the end of an alternative to the end of the switch statement.
Program: Control09.java
// Learning Object Control09
//    switch statements
public class Control09 {
    public static void main(/*String[] args*/) {
        int year = 2001;
        int month = 4;
        int days;
        switch (month) {
            case 2:
                days = (year % 4 == 0) ? 28 : 29;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
            default:
                days = 31;
        }
        System.out.println(days);
    }
}
This program computes the number of days in a month.
  • The variables are allocated and the first two, year and month, are given initial values.
  • The switch statement chooses a case depending on the value of the variable month. Jeliot displays Entering a switch statement.
  • The case associated with 4 is selected. Jeliot displays This case is selected. The assignment statement assigns 30 to days.
  • The assignment statement assigns 31 to days.
  • The switch statement terminates and Jeliot displays Exiting a switch statement.
  • The value of days is printed.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

java

Popular java Topics