Skip to main content
Logo image

Problem Solving with Algorithms and Data Structures using Java: The Interactive Edition

Section 1.12 Control Structures

As we noted earlier, algorithms require two important control structures: selection and iteration. Java supports both of these in various forms. Programmers can choose the statement that is most useful for the given circumstance.
Selection statements allow programmers to ask questions and then, based on the result, perform different actions. Most programming languages provide two versions of this useful construct: the if...else and the if. The following code fragment is an example of a binary selection using the if...else statement.
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
double n = input.nextDouble();

if (n >= 0) {
    System.out.println(Math.sqrt(n));
} else {
    System.out.println("Number can not be negative.");
}
In this example, the value of variable n is checked to see if it is greater than or equal to zero. If it is, the program prints the square root of the number. If it is not, the statement performs the else clause and tells the user that the number cannot be negative.
The condition for the if must be enclosed in parentheses. The body of the if and else clause is enclosed in braces. If there is exactly one statement in the clause, you may omit the braces, but doing so may lead to code that is ambiguous and difficult to read. Thus, we strongly recommend that you always use braces (with one exception that we will cover later).
Selection constructs, as with any control construct, can be nested so that the result of one question helps decide whether to ask the next. For example, assume that score is a variable holding a reference to a score for a computer science test.
String grade;

if (score >= 90) {
    grade = "A";
} else {
    if (score >= 80) {
        grade = "B";
    } else {
        if (score >= 70) {
            grade = "C";
        } else {
            if (score >= 60) {
                grade ="D";
            } else {
                grade = "F";
            }
        }
    }
}

System.out.println("The grade is " + grade + ".");
This fragment will classify a value called score by printing the letter grade earned. If the score is greater than or equal to 90, the variable grade will be assigned "A". If it is not (else), the next question is asked. If the score is greater than or equal to 80, then it must be between 80 and 89 since the answer to the first question was false. In this case, the grade becomes "B" is printed. You can see that using correct indentation pattern helps to make sense of the association between if and else.
The drawback of this indentation is that the code tends to march off the page to the right, which does not help readability. We can, however, consider the block in lines 6-18 as a single statement, and use the “omit braces” shortcut. Similarly, we can eliminate braces around the statement in lines 8-17 and so on. We can then follow the else immediately by an if with the resulting code:
String grade;

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 60) {
    grade ="D";
} else {
    grade = "F";
}

System.out.println("The grade is " + grade + ".");
Note that the final else is still necessary to provide the default case if all other conditions fail.
The else clause is not required in Java; an if without an else is called a single-way selection construct. In a single-way selection, if the condition is true, an action is performed. When the condition is false, processing simply continues on to the next statement after the if. For example, the following fragment will first check to see if the value of a variable n is negative. If so, then it is modified by the absolute value function. Regardless, the next action is to compute the square root.
if (n < 0) {
    n = Math.abs(n);
}

System.out.println(Math.sqrt(n));
For iteration, Java provides a standard while statement and two varieties of the for statement. The while statement repeats a body of code as long as a condition evaluates to true. Generally, we use a while loop for indeterminate loops, where we do not know how many times the loop has to iterate. Consider this program, where we ask the user repeatedly enter numbers they want to sum, entering zero when they are finished. In this case, we have no idea how many times the user will enter numbers before finishing:
import java.util.Scanner;

class SumNumbers {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        double sum = 0.0;

        System.out.print("Enter a number, or zero to quit: ");
        double n = input.nextDouble();
        while (n != 0) {
            sum = sum + n;
            System.out.print("Enter another number, or zero to quit: ");
            n = input.nextDouble();
        }

        System.out.format("The sum is %.3f%n", sum);
    }
}
The condition on the while statement is evaluated at the start of each repetition. If the condition evaluates to true, the body of the statement will execute. While Java does not require you to indent the body of the loop, we strongly suggest you do so to make your code more readable.
The while statement is a very general-purpose iterative structure that we will use in a number of different algorithms. In many cases, a compound condition will control the iteration. Consider the following code to sum the elements in an array up to, but not including, the first negative number:
int index = 0;
double sum = 0.0;
double [] data...; // code to initialize array

while ((index < data.length) && (data[index] >= 0.0) {
   sum = sum + data[index];
   index = index + 1;
}
Listing 1.12.1. Example of while loop
The compound condition would cause the body of the statement to be executed only in the case where both parts of the condition are satisfied. The value of the variable index would need to be less than the array length (to avoid “falling off the edge of the earth”), and the value array element at the current index would need to be greater than or equal to zero.
Sometimes, though, we do know how many iterations a calculation will require. We can use the for loop in conjunction with many of the Java collections to iterate over the collection’s members.
The first version of the for statement combines the elements of this while loop:
initialization;
while (condition) {
    loop body;
    action; // update variable used in condition
}
Into a single statement of this form:
for (initialization; condition; action) {
      loop body;
}
Here is a program fragment that does the same thing as Listing 1.12.1, but uses a for loop to sum all the items up to, but not including, the first negative value in an array:
double sum = 0.0;
for (int index = 0; (index < data.length) && (data[index] >= 0.0); index++) {
    sum = sum + data[index];
}
Listing 1.12.2. Example of for loop
If you want to access every element in the collection but do not need to use the index as a part of the calculation, you can use the extended for loop. The following example adds up all the items in the data array:
double sum = 0.0;
for (double item: data) {
    sum = sum + item;
}
The loop will assign each item in the data array to the loop variable item, one after another, and you can use that value in the loop body. You may use any variable name you wish; we used item here because it is a meaningful name.

Exercises Self Check

1.

Write a Java program that uses a while loop to continually prompt the user to enter a number greater than zero until the user does so. (Hint: as long as the number is not greater than zero, you must keep asking.)

2.

Here five scores for a student’s assignments: 98.2, 85.9, 94.0, 92.0, 88.5 and the weight of each assignment: 0.3, 0.2, 0.3, 0.1, 0.1 (that is, the first assignment is worth 30% of the total grade, the second is worth 20%, and so on). Write a program which calculates a weighted sum by multiplying each score by its corresponding weight and summing them up. Your program must use a for loop.

3.

Write a Java program that takes an array of integers and produces the sum of the odd-indexed numbers and the sum of the even-indexed numbers. For example, in this array: {4, 2, 8, 5, 9}, the even-numbered index elements are 4, 8, and 9, which add up to 21. The odd-numbered index elements are 2 and 5, which sum to 7. Your program must work with any array, not just this example array. Try to do it with only one loop (hint: if is your friend).
You have attempted of activities on this page.