Object-Oriented Programming with Java · Lecture Notes

Chapter 1.4: Flowcharts

Before a program is written, the solution has to be planned on paper. A flowchart draws this plan with boxes and arrows. These notes introduce the symbols of flowcharts and the rules for drawing them, and show the Java counterpart of each symbol. Then come the three kinds of flow that are the building blocks of all algorithms: sequential, conditional and repetitive flow. Each kind is explained with a diagram, a Java program written from that diagram, and a step-by-step trace of the program. The counter, accumulator, flag and sentinel patterns often used in loops, early exit and nested loops are treated separately. The last sections cover the subprogram, that is, the method in Java, tracing a diagram at a desk, and the choice of test cases. All the Java programs in the examples were compiled and run with JDK 21; the values in the trace tables were checked against these runs.

Learning outcomes

Concept
Explain the relationship between an algorithm and a flowchart; say what a flowchart is good for and where it falls short.
Symbols
Recognize the Start/End, input, process, decision, loop, print, connector and subprogram symbols; choose the right symbol for each step; apply the drawing rules.
Control structures
Tell sequential, conditional and repetitive flow apart; draw a diagram for each; tell a structured diagram from an unstructured one.
Tracing
Execute a diagram or a program step by step on a given input by building a trace table; notice boundary errors and infinite loops.
From diagram to Java
Translate each symbol into its Java counterpart: nextInt(), assignment, if/else, while, for, println, a method call; tell the errors the compiler catches from those it cannot.
Design and testing
Plan a simple problem first with a diagram and then turn it into a program; choose test cases that exercise every path and the boundary values.

1.4.1Algorithm and flowchart

A Java program consists of statements that the computer executes in order. But starting to write a program directly at the keyboard often gives a faulty result. First you think about how to solve the problem and fix the steps of the solution; only then are these steps translated into the programming language. The flowchart is one of the oldest and most widespread tools for the stage of fixing the steps.

1.4.1.1From algorithm to drawing

Definition 1.4.1

An algorithm is an ordered and finite plan of the steps to follow to solve a problem or carry out a task. Every step is clear; with the same input the same result is reached every time.

Definition 1.4.2

A flowchart is a drawing that shows visually the steps of an algorithm, the connections between the steps and the control mechanisms. Each step is drawn with a symbol. The order in which the steps run is shown by arrows, that is, by flow lines.

The relationship between the two definitions can be explained with a recipe. A recipe is an algorithm: prepare the ingredients, boil the water, brew the tea. The same recipe drawn with boxes and arrows is a flowchart. It is also possible to describe the recipe in writing. But a decision like "if the water has not boiled, wait; if it has, brew" or a repetition like "wait until it boils" is easily overlooked in text. In a drawing, the decision stands out at once as a diamond and the repetition as an arrow looping back. Figure 1.4.1 is the diagram of this recipe.

StartPut water in the kettleHas the water boiled?WaitBrew the teaEndNY
Figure 1.4.1: The flowchart of the tea-brewing algorithm. The No (N) exit of the decision box goes to the "Wait" box; the arrow leaving it returns to the top of the decision box. When the water boils, the Yes (Y) exit leads on to the "Brew the tea" step.

The diagram is read from top to bottom. Execution begins at the round-ended Start box and proceeds along the arrows. "Put water in the kettle" is a process and is drawn with a rectangle. "Has the water boiled?" is a question; since its answer is Yes or No, it is drawn with a diamond and has two exits. The No exit goes to the "Wait" box and from there back to the question itself. So the question is asked again and again until the answer is Yes. This small drawing contains all three kinds of flow: steps one after another, a decision and a repetition.

A flowchart is not tied to a programming language. A Java, C or Python program can be written from the same diagram. So the diagram is not the program itself but the plan of the program. The correctness of the plan is checked on paper; only after that is code written.

1.4.1.2Benefits and limits

The most important benefit of a flowchart is that it makes a complex process visible at a glance. Which step follows which, and in which situation a step is skipped or repeated, are plainly visible with arrows. This visibility lets mistakes be found before code is written. For example, if only the Yes exit of a decision box has been drawn, it is immediately clear that nobody has thought about what happens in the No case.

The second benefit of the diagram is documentation. A process, for example a registration procedure or the operating steps of a machine, is described with a flowchart in reports and technical documents. The third benefit is that it provides a common language. Not everyone in a team may know the same programming language, but everyone can read a flowchart.

The diagram has limits too. The diagram of a large program spills over several pages and becomes hard to read. When the algorithm changes, the diagram has to be redrawn, which takes time. As detail increases, so does the number of symbols. In that case pseudocode, which writes the algorithm in semi-natural language, is more practical. In practice flowcharts are used for small and medium-sized algorithms, or to show the outline of a large program.

The development of a program usually goes in the order of Figure 1.4.2. The problem is defined, the solution steps, that is, the algorithm, are determined, the algorithm is put into a flowchart, the diagram is translated into a Java program, and the program is run and tested. If testing gives a wrong result, we go back and fix the algorithm.

problemalgorithmflowchartJava programrun, testwrong result: go back to the algorithm
Figure 1.4.2: The typical working order: problem → algorithm → flowchart → Java program → running and testing. If testing gives a wrong result, the dashed arrow goes back to the algorithm.

1.4.2Symbols and drawing rules

The shape of each symbol in a flowchart tells the kind of that step. Even before reading the text inside a box, the reader can tell from its shape whether a step is a read, a computation or a decision. So choosing the symbols correctly is the first condition for a diagram to be understandable.

1.4.2.1Basic symbols

The shapes of the symbols are based on an international standard, ISO 5807. Figure 1.4.3 shows the eight most commonly used symbols.

StartStart / EndOval. Where the algorithm starts and ends.
Read xInput / OutputParallelogram. Reading data from the keyboard (input).
x = x + 1ProcessRectangle. Computation, assignment.
x > 0 ?DecisionDiamond. A Yes/No question, two exits.
i = 1; i ≤ 5; i++LoopHexagon. A repetition a fixed number of times.
Print xPrintWavy bottom edge. Writing the result to the screen or to paper.
AConnectorSmall circle. The point where lines join.
Flow lineArrow. The order of the steps; execution proceeds in the direction of the arrow.
Figure 1.4.3: The basic flowchart symbols and their roles.

The Start/End symbol is a rectangle with rounded sides, that is, an oval. Every diagram has a Start symbol; execution begins there. The End symbol is where the algorithm finishes.

The Input symbol is a parallelogram and shows a step where data is taken from outside. A parallelogram labeled "Read num" means the user will enter a number at the keyboard and this number will be put into the variable named num. Some sources draw output, that is, writing to the screen, with a parallelogram too. In these notes a separate symbol is used for writing to the screen, the Print symbol with a wavy bottom edge. The wavy edge recalls a sheet of paper; the old name of the symbol is "document".

The Process symbol is a plain rectangle. A computation or an assignment is written inside it: "area = a × b", "counter = counter + 1". A process box has a single entry and a single exit.

The Decision symbol is a diamond. A question whose answer is Yes or No is written inside: "num > 0 ?". The decision box is the only symbol with two exits. One of the exits is labeled Yes (Y), the other No (N).

The Loop symbol is an elongated hexagon. It summarizes a job repeated a fixed number of times in a single box: "i = 1; i ≤ 10; i++". The three parts inside the hexagon are the initialization, the condition and the update. The Connector is a small circle. It shows where several arrows join; for example, when the two branches of a decision finish their work, they meet at the connector. The flow line is the arrow that connects the symbols. Execution always proceeds in the direction the arrow points.

1.4.2.2Java counterparts of the symbols

When a diagram is translated into a Java program, each symbol corresponds to a specific Java construct. Table 1.4.1 gives this mapping. The table can be used like a dictionary in going from diagram to code.

Table 1.4.1: Flowchart symbols, the expression written in the box, and the Java counterpart.
SymbolText in the diagramJava counterpart
Start / EndStart … Endpublic static void main(String[] args) { … }
InputRead numint num = scanner.nextInt();
Processresult = num1 + num2int result = num1 + num2;
Decisionresult = 0 ?if (result == 0) { … } else { … }
Decision + back arrowcounter ≤ 10 ?while (counter <= 10) { … }
Loopi = 1; i ≤ 10; i++for (int i = 1; i <= 10; i++) { … }
PrintPrint resultSystem.out.println(result);

The first row of the table says that everything between the Start and End symbols of the diagram is written in the body of the main method in Java. The program starts at the first line of the main method and ends when it reaches the last line. For the Input symbol, Java uses the java.util.Scanner class. At the start of the program, an object that reads from the keyboard is created with the line Scanner scanner = new Scanner(System.in);. Then for each "Read" box, scanner.nextInt() (integer), scanner.nextDouble() (decimal number) or scanner.next() (word) is called.

The decision symbol has two different Java counterparts. If there is no arrow going back, the decision is an if statement: the question is asked once, and one of the two branches runs depending on the answer. If an arrow leaving one of the branches of the decision returns to the top of the decision box, the structure is a loop and is written with while. So the same diamond can be an if or a while, depending on where the arrows go. The hexagonal loop symbol corresponds directly to the for statement.

The point where most mistakes are made in translation is the equals sign. In a process box in the diagram, "=" means assignment: the value on the right is computed and put into the variable on the left. In a decision box, "=" means comparison: the question is whether two values are equal. Java writes these two meanings with different signs: assignment with =, comparison with ==. Similarly, "mod" (the remainder of a division) in the diagram is the % operator in Java; the signs ≤ and ≥ are written <= and >=, and ≠ is written !=.

Common mistake

The question "result = 0 ?" in the decision box is translated into Java as if (result = 0). This line does not compile. The JDK 21 compiler gives this message: error: incompatible types: int cannot be converted to boolean. result = 0 is an assignment and its value is the int 0; if expects a boolean condition. The right way is if (result == 0). In C the same mistake compiles and silently runs wrongly; Java's type checking catches it at compile time.

1.4.2.3Other symbols

The basic symbols are enough for most diagrams. To split long diagrams or to show where data is written, ISO 5807 has other symbols too. Figure 1.4.4 shows six of them.

average()SubprogramRectangle with double side lines. Calls a sequence of steps drawn separately. Java: a method call.
BOff-page connectorPentagon pointing down. The diagram continues on another page; the same letter is written at both ends.
gradesData storeCylinder. Saving to a file or database and reading from it.
Read xManual inputQuadrilateral with a slanted top edge. Some sources draw keyboard input with this.
commentCommentOpen square bracket. A note that does not take part in the flow. Java: a // comment.
i = 1PreparationHexagon. Its name in ISO 5807 is preparation; used for the initial setup of a loop.
Figure 1.4.4: Additional flowchart symbols.

The Subprogram symbol is a rectangle with vertical lines added at its two sides. It calls a sequence of steps drawn elsewhere; its Java counterpart is a method call. One part of a long diagram is drawn separately and called with this symbol in the main diagram. The off-page connector is used when a diagram does not fit on a single page. A letter is written in the pentagon at the end of the first page, for example B. The pentagon at the start of the second page carries the same letter; the reader follows the flow by this letter.

The Data store symbol is a cylinder and shows data written to a lasting place, for example a file or a database. The Manual input symbol is used to emphasize keyboard input separately; many sources prefer the parallelogram instead. The Comment symbol is not part of the flow. It is for jotting a note next to a box; it resembles the // comment in Java. Just as the compiler ignores comments, a person following the diagram does not include comments in the execution.

The shape of the Preparation symbol is the same as the loop symbol. In ISO 5807 this hexagon is called "preparation" and shows the setup before a job begins. The use of this symbol to gather a loop's initial value, condition and update in one box comes from here.

1.4.2.4Drawing rules

A flowchart is built in a few steps. First the operations are determined: which inputs will be read, which computations done, which outputs written? Then the steps are put in a logical order. Next all the symbols are connected to one another with flow lines. Finally, decision points are added for the steps that depend on a condition.

The following rules are observed to keep the drawing readable:

  • A diagram has a single Start and at least one End. Two separate End symbols do not break the rule; but two Start symbols leave unclear where execution begins.
  • Flow is read from top to bottom and left to right. Arrows that go outside this direction, for example the back arrow of a loop, are clearly shown with the arrowhead.
  • Every symbol except a decision has a single exit. Only the decision symbol has two exits.
  • Decision exits are always labeled Yes/No (Y/N). An unlabeled exit does not say which answer it belongs to.
  • Lines do not cross one another. If a crossing is unavoidable, the lines are joined at a connector.
  • Short and clear expressions are written in the boxes: "Read a, b", "area = a × b", "Print area". Long sentences make the diagram crowded.

1.4.2.5Step-by-step drawing: the area of a rectangle

The rules can be applied to a small problem. The problem is to find the area of a rectangle whose side lengths are entered at the keyboard.

Example 1.4.1

Problem: print the area of a rectangle on the screen from the two side lengths read from the keyboard.

  1. Skeleton. First a Start and an End symbol are drawn. All the steps will go between these two.
  2. Inputs. Two side lengths are needed to compute the area. They are read from the keyboard: a parallelogram labeled "Read a, b" is added.
  3. Process. The area is the product of the two sides. A rectangle labeled "area = a × b" is added. This box computes the product and assigns the result to the variable area.
  4. Output. The computed area is written on the screen: a Print symbol labeled "Print area" is added.
  5. Connecting. The symbols are connected with flow lines in a logical order: Start → Read → Process → Print → End. There is no decision point in this problem; the flow is sequential.
  6. Testing. The diagram is tried with an input. If a = 4 and b = 3 are entered, area = 4 × 3 = 12 is computed and 12 is seen on the screen. The expected result is also 12; the diagram works correctly.
StartRead a, barea = a × bPrint areaEnda = 4, b = 3area = 12on screen: 12
Figure 1.4.5: The diagram that finds the area of a rectangle. The red notes on the right show the values the variables take in the test with the input a = 4, b = 3.

Once the diagram is ready, translating it into Java is mechanical. With the help of Table 1.4.1 each symbol becomes a line:

import java.util.Scanner;

public class RectangleArea {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int area = a * b;
        System.out.println(area);
        scanner.close();
    }
}

The "Read a, b" in the parallelogram becomes two separate nextInt() calls. The process box turns into the line int area = a * b;; the × sign in the diagram is written * in Java. The Print symbol is the line System.out.println(area);. When the program is run with the input 4 and 3, it prints 12 on the screen; this is the same as the result in the diagram's test. Each box runs only once, no step is skipped and no step is returned to. These properties make up the definition of sequential flow.

1.4.3Control structures

Which statement of a program runs in which order is called control flow. In a flowchart, the control flow is the arrows themselves. However tangled the arrows may look, every well-drawn diagram is built from only three basic structures.

1.4.3.1The three kinds of flow

Step 1Step 2Step 3 condition ?PQYN condition ?bodyYN
Figure 1.4.6: The three control structures. (a) Sequential flow: the steps run in order, once each. (b) Conditional flow: depending on the condition, P or Q runs; the paths join at the connector. (c) Repetitive flow: while the condition holds the body repeats; when the condition is false, execution continues from the N exit.
Definition 1.4.3

Sequential flow is flow in which the steps run in the order they are written and each runs exactly once. Conditional flow is flow in which one of two or more paths is chosen according to the result of a condition. Repetitive flow, or a loop, is flow in which some steps run again and again as long as a condition holds.

Figure 1.4.6 shows the three structures side by side. In sequential flow the arrows always go down; no arrow leaves or returns. In conditional flow two arrows leave a decision box; these two paths then join again at a connector. In repetitive flow, an arrow returns back to the top of the decision box. An arrow going back is the sure sign of a loop.

It has been shown mathematically that these three structures are sufficient. Corrado Böhm and Giuseppe Jacopini proved the following result in an article they published in 1966:

Theorem 1.4.1 (Structured program theorem, Böhm–Jacopini)

Every computable algorithm can be written using only three structures: sequence, selection and repetition. These structures are either arranged one after another or nested inside one another.

The counterpart of the theorem in Java is clear. Sequence is statements written one after another. Selection is if/else, and repetition is the while and for statements. Java's other control statements, for example switch or do-while, are shorthand for these three structures. The theorem guarantees that even a complex problem can be solved with these three pieces. The same idea is followed when designing a diagram: the problem is divided into sequence, selection and repetition pieces and the pieces are combined.

1.4.3.2Structured and unstructured diagrams

Definition 1.4.4

A structured flowchart is a flowchart in which every control structure has a single entry and a single exit. The structures are either arranged one after another or nested inside one another; no arrow enters from outside into the middle of a structure.

StartAK ?BCDEndYN StartAK ?BCL ?DEndYNYN
Figure 1.4.7: (a) A structured diagram: the decision K with the branches B and C forms a block with a single entry and a single exit inside the dashed frame. (b) An unstructured diagram: the Yes arrow of the decision L enters the middle of the other branch (C), and the No arrow goes back to A.

In the diagram on the left of Figure 1.4.7, the block that starts with the decision K is shown with a dashed frame. A single arrow enters the block from the top and a single arrow leaves from the bottom. The branches B and C stay inside the block and join at the connector. It is possible to think of this block as a single box without knowing what is inside. The person reading the diagram first sees A, then the block, then D.

In the diagram on the right, the Yes arrow of the decision L enters the middle of the other branch, the box C. The No arrow goes back to A. In this case box C can be reached by two different paths; A too is reached both from Start and from L. To tell which path a box was reached by, the whole diagram has to be traced. The arrows tangle with one another like spaghetti; that is why such flow is called "spaghetti flow". Spaghetti flow is hard to follow and to find a bug in.

In old programming languages such jumps were written with the goto statement. The statement goto label; would take execution to any place in the program. In Java goto is a reserved word but has no meaning; it cannot be used. A program containing goto start; does not compile on JDK 21, with the message error: illegal start of expression. The designers of Java deliberately kept this word out of the language.

Java has two limited jumps: break and continue. break ends the loop it is in at once. continue skips the rest of that iteration of the loop and moves to the next iteration. These two statements take execution not to an arbitrary place in the program but only to the end or the start of the loop they are in. So no spaghetti flow arises.

A practical consequence of the Böhm–Jacopini theorem is this: every unstructured diagram can, if needed, be turned into a structured one by adding a boolean flag variable. The flag records whether an event has happened; this variable is tested in place of the jump.

1.4.4Sequential flow

Sequential flow is the simplest of the three structures. Still, every program contains sequential parts: giving variables initial values, reading input, computing a formula, writing the result. Even the conditional and repetitive structures consist of sequential steps inside themselves.

1.4.4.1Properties of sequential flow

StartRead a, bc = a + bPrint cEnd
Figure 1.4.8: Sequential flow: Start → Read a, b → c = a + b → Print c → End. The flow proceeds without branching or returning.

Sequential flow is arranging the jobs to be done one after another in a logical order. Figure 1.4.8 draws such a flow from left to right; the same flow can also be drawn from top to bottom. Sequential flow has four properties.

It is simple. There is no branching or repetition. To understand the flow it is enough to follow the arrows in order.

It is easy to maintain. Since the steps run in the order they are written, it is easy to find where the program is when looking for a bug. Debugging is nothing but checking the steps one by one.

Order matters. If a step uses the result of the previous one, it cannot change places. The step "c = a + b" cannot be done before a and b are read. But the order of independent steps can be changed. If the places of "Read a" and "Read b" are swapped, the result does not change; only the order in which the user is asked changes.

There is no going back. Each step runs exactly once. No step is skipped and no earlier step is returned to. A sequential flow of N steps always ends in N steps, independent of the input.

Common mistake

If the addition step is written before the numbers are read, the addition is attempted with values not yet known. In the diagram this is a logic error. In Java, if variables are declared but have not yet received a value, the compiler catches the mistake:

int num1, num2;
int result = num1 + num2;     // the numbers have not been read yet
num1 = scanner.nextInt();
num2 = scanner.nextInt();

JDK 21 gives two errors for this fragment: error: variable num1 might not have been initialized and the same for num2. Java never allows a local variable that has not received a value to be read. This rule is called definite assignment. For each variable the compiler examines all paths of the program; if there is a path that reaches the point where the variable is used without it having received a value, it does not compile the program.

1.4.4.2The sum of two numbers

The classic example of sequential flow is printing the sum of two numbers entered at the keyboard. The algorithm for the problem has six steps:

  1. Start.
  2. Read the first number (num1).
  3. Read the second number (num2).
  4. Add the two numbers and assign the result to the variable result.
  5. Write the result on the screen.
  6. End.
StartRead num1Read num2result = num1 + num2Print resultEnd
Figure 1.4.9: The flowchart that prints the sum of two numbers. Each step of the algorithm corresponds to one symbol.

Figure 1.4.9 is the diagram of this algorithm. Each step of the algorithm has become a symbol: Start and End are ovals, the two reading steps are parallelograms, the addition is a rectangle, and writing to the screen is the Print symbol. The algorithm has six steps and the diagram has six symbols. This one-to-one correspondence is a typical property of sequential flow.

The reading steps are drawn as two separate parallelograms. A single "Read num1, num2" box would also have been correct. Two separate boxes show clearly that in the Java program too there will be two separate reads and two separate prompt messages.

1.4.4.3From diagram to Java: the sum program

The diagram is translated into the following Java program:

import java.util.Scanner;

public class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("First number: ");
        int num1 = scanner.nextInt();
        System.out.print("Second number: ");
        int num2 = scanner.nextInt();
        int result = num1 + num2;
        System.out.println("Result: " + result);
        scanner.close();
    }
}

The program runs line by line as follows. The import statement on line 1 brings the Scanner class from the java.util package into the program. Without this line the compiler does not recognize the name Scanner. Line 3 defines the class named AddTwoNumbers; in Java every program is written inside at least one class, and the file must be named AddTwoNumbers.java.

The main method on line 4 is the Start symbol in the diagram; the program begins here. On line 5 the Scanner object that will read from the keyboard is created. System.in is standard input, that is, the keyboard.

Lines 6 and 7 are the first parallelogram. print first tells the user what to enter. Unlike println, it adds no line end; so the number the user types appears on the same line as the message. scanner.nextInt() waits for the user to type an integer and press Enter. The value read is assigned to the variable num1. Lines 8 and 9 do the same job for the second number.

Line 10 is the process box: int result = num1 + num2;. Line 11 is the Print symbol. In the expression "Result: " + result, the + operator concatenates a string and a number; the number is converted to a string and appended. Line 12 closes the Scanner object. On line 13 main ends; this is the End symbol in the diagram.

Table 1.4.2 is the trace of the program when the user enters 7 first and then 5. In the table each row corresponds to a diagram box and the lines of code that make up that box. The "—" sign shows that the variable has not yet received a value.

Table 1.4.2: Trace of the AddTwoNumbers program with the input 7 and 5.
LineDiagram boxnum1num2resultAdded to the screen
4–5Start; the Scanner is created———
6–7Read num17——First number: 7
8–9Read num275—Second number: 5
10result = num1 + num27512
11Print result7512Result: 12
12–13End7512

The conversation seen on screen is as follows; the numbers the user types come right after the messages:

First number: 7
Second number: 5
Result: 12

The trace table shows the properties of sequential flow with numbers. The table has six rows and each diagram box appears exactly once. No row has been skipped and no row has been returned to. The result variable receives a value only on line 10; before that, "—" is shown. Even if the input changes, the number of rows in the table does not; only the values in the cells change. For example, if −3 and 10 are entered, the program prints Result: 7.

Common mistake

nextInt() reads only integers. If the user types "abc" or "7,5", the program stops with an error message: Exception in thread "main" java.util.InputMismatchException. The "Read num" box in the diagram assumes the user will enter data of the right type. This assumption holds in the program too; catching invalid input needs a separate decision or exception handling. For decimal numbers nextDouble() is used; this method expects the decimal separator set in the computer's regional settings.

1.4.5Conditional flow

A sequential program follows the same steps every time it runs. In most problems, however, what has to be done depends on the situation. If the grade is below 50 the student fails, otherwise passes. If a number is even one message is written, if odd another. Conditional flow gives the program this flexibility.

1.4.5.1The decision structure

In conditional flow one of two or more possibilities is chosen. The structure has three parts. The decision point (K) contains a condition question; the answer to the question is Yes or No. If the answer is Yes, the flow goes toward the process P. If the answer is No, the flow goes toward the process Q. When the two paths finish their work, they join at a connector and the flow continues with the next step.

K: condition ?PQnext stepYesNo
Figure 1.4.10: The general form of conditional flow. If the condition K is true, P on the Yes branch runs; if false, Q on the No branch runs. The two branches join at the connector.

The Java counterpart of this structure is the if/else statement:

if (K) {
    P;   // condition true
} else {
    Q;   // condition false
}

K in the parentheses is a boolean expression whose value is true or false. In Java the condition must be a boolean; as in C, zero or a nonzero integer cannot stand in for a condition. The curly braces gather the statements that run in a branch into a block. If a branch has a single statement, the braces may be omitted. But when a second statement is later added to that branch, a mistake is easily made; so always writing the braces is a good habit.

Conditional flow gives a program three things. Flexibility: the program behaves differently for different inputs. Decision making: an operation is done only when needed; for example, division by zero is attempted only if the divisor is not zero. Control of the code: the program checks a situation and acts accordingly; for example, it notices invalid input and writes a warning.

The decision structure also has a one-branch form. If there is no job to do on the No branch, that branch goes straight to the connector. This is a one-way decision and is written in Java as an if without else: if (x > 0) System.out.println(x);. If the condition is false, nothing is done and the flow continues with the next statement.

1.4.5.2Is the number odd or even?

The problem is to print whether an entered integer is odd or even. A number being even means that the remainder of its division by 2 is 0. The remainder of a division is found with the mod operation: 7 mod 2 = 1, because 7 = 3 × 2 + 1. 8 mod 2 = 0, because 8 = 4 × 2 + 0. The algorithm has seven steps:

  1. Start.
  2. Read the number.
  3. Take the number mod 2 and assign it to the result variable.
  4. If the result is 0 go to 5, otherwise go to 6.
  5. Write "even" on the screen, go to 7.
  6. Write "odd" on the screen.
  7. End.

The "go to …" expressions in the algorithm stand out. In an algorithm described in words, branching can be shown only with step numbers like this. In a diagram, the same branching is drawn with a decision box and two arrows; step numbers are not needed.

StartRead numresult = num mod 2result = 0 ?Print evenPrint oddEndYN
Figure 1.4.11: The odd/even diagram. The process box computes the remainder, and the decision box asks whether the remainder is 0. The Y branch writes "even", the N branch "odd"; the two branches join at End.

The Java counterpart of the diagram is as follows:

import java.util.Scanner;

public class OddOrEven {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Number: ");
        int num = scanner.nextInt();
        int result = num % 2;
        if (result == 0) {
            System.out.println("even");
        } else {
            System.out.println("odd");
        }
        scanner.close();
    }
}

The "mod" in the diagram is the % operator in Java. Line 8 computes result = num % 2. The if on line 9 is the decision box and asks the question result == 0. If the condition is true, line 10 runs; if false, line 12; never both. The else on line 11 is the start of the No branch.

Table 1.4.3 summarizes two separate runs of the program with the inputs 7 and 8. When 7 is entered, result = 7 % 2 = 1. 1 == 0 is false, the flow goes to the No branch, that is, the else block, and "odd" is printed. In this run line 10 in the if block never runs. When 8 is entered, result = 0, "even" is printed from the Yes branch, and this time line 12 is skipped. In each run only one of the two branches runs; the two paths join at End.

Table 1.4.3: Two runs of the OddOrEven program.
InputProcess boxDecisionExitLine that runsOutput
77 % 2 = 11 == 0 → falseNo12odd
88 % 2 = 00 == 0 → trueYes10even

Negative numbers need separate attention. In Java the result of the % operation takes the sign of the dividend. So the value of -3 % 2 is −1, not 1; and -4 % 2 is 0. Since the diagram in the slides sets up the condition as "result = 0 ?", it is not affected by this detail: since −1 ≠ 0, "odd" is correctly printed for −3. If the condition had been set up as "result = 1 ?", the situation would change. Table 1.4.4 compares the two conditions with the inputs −3, 7 and 0.

Table 1.4.4: The effect of the condition in the decision box on the result for a negative input (in Java the remainder takes the sign of the dividend).
Inputnum % 2Condition == 0 (from the slides)Condition == 1
−3−1No → oddNo → even
71No → oddYes → odd
00Yes → evenNo → even
Common mistake

Writing the odd check as if (num % 2 == 1) gives a wrong result for negative odd numbers. For −3, the value of -3 % 2 is −1, so the condition is false and the program prints -3 even. The compiler does not catch this mistake, because the code follows Java's rules; the error is in the logic. The safe way is to test evenness: num % 2 == 0. Whether the remainder is −1 or 1, the number falls into the "odd" branch. When a remainder that is always non-negative is needed, as in mathematics, Math.floorMod(num, 2) is used; the value of Math.floorMod(-3, 2) is 1.

1.4.5.3Nested decisions: positive, negative, zero

A decision box has only two exits. When there are three possibilities, two decision boxes are connected one after the other: the No exit of the first question goes to the second question. Figure 1.4.12, which finds whether a number is positive, negative or zero, shows this structure.

StartRead numnum > 0 ?Print positivenum < 0 ?Print negativePrint zeroEndYNYN
Figure 1.4.12: A nested decision. The No exit of the first decision (num > 0 ?) goes to the second decision (num < 0 ?). Of the three Print boxes, only one runs in each run.

The first decision asks the question "num > 0 ?". If the answer is Yes, "positive" is printed and the flow goes to End; the second question is never asked. If the answer is No, the number is either negative or zero. To separate these, the second decision asks the question "num < 0 ?". If Yes, "negative" is printed; if No, "zero". A number reaching the No exit of the second decision is neither positive nor negative; only one possibility is left, and that is zero. So a third question is not needed.

In Java a nested decision is written with an else if chain:

Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
if (num > 0) {
    System.out.println("positive");
} else if (num < 0) {
    System.out.println("negative");
} else {
    System.out.println("zero");
}

else if is not a separate statement in Java. In the else branch of the first if there is a second if statement; the curly braces let this structure be written at a single level. That the second decision in the diagram is attached to the No exit of the first shows exactly this nesting.

Table 1.4.5 traces three runs of the program. When −4 is entered, the first condition -4 > 0 is false; the flow goes from the No exit to the second decision. -4 < 0 is true and "negative" is printed; the last else branch is skipped. When 0 is entered, 0 > 0 is false, because 0 is not positive. 0 < 0 is false too; since both conditions are false, the last else runs and "zero" is printed. When 5 is entered, the first condition is true and the second condition is never tested.

Table 1.4.5: Three runs of the nested decision program. The number of decisions tested is 1 or 2 depending on the input.
Input1st decision2nd decisionOutput
−4−4 > 0 → false−4 < 0 → truenegative
00 > 0 → false0 < 0 → falsezero
55 > 0 → truenot askedpositive
StartRead numnum > 0 ?Print positivenum < 0 ?Print negativePrint zeroEndYNYNoutput: negative StartRead numnum > 0 ?Print positivenum < 0 ?Print negativePrint zeroEndYNYNoutput: zero
Figure 1.4.13: Two runs of the nested decision. (a) Input −4: the No exit of the first decision and the Yes exit of the second are followed and "negative" is printed. (b) Input 0: the No exits of both decisions are followed and "zero" is printed. Highlighted arrows show the path followed.

Since there are three branches, trying the diagram completely takes at least three inputs. Each input runs a different Print box. This is the first example of the idea of path coverage used in choosing test cases: every exit of every decision box must be tried at least once.

Example 1.4.2

In a diagram that converts a grade between 0 and 100 into a letter grade there are four possibilities: A if grade ≥ 85, B if ≥ 70, C if ≥ 50, otherwise F. For four possibilities, three decision boxes are connected one after another. The Java counterpart is an else if chain:

if (grade >= 85) {
    System.out.println("A");
} else if (grade >= 70) {
    System.out.println("B");
} else if (grade >= 50) {
    System.out.println("C");
} else {
    System.out.println("F");
}

When 72 is entered, 72 >= 85 is false and 72 >= 70 is true; "B" is printed and the third decision is never tested. When 45 is entered, all three conditions are false and "F" is printed. For 72 two decisions are tested, for 45 three. In the second condition there is no need to ask separately grade < 85: only grades below 85 reach that decision. Boundary values also fall into the right branch: 85 → A, 84 → B, 70 → B, 50 → C, 49 → F.

1.4.5.4Compound conditions: AND, OR

Some decisions depend on two conditions at once. For a person to be able to drive a car, they must be both 18 or older and hold a license. This is an AND condition. If being a student or being over 65 is enough to benefit from a discount, this is an OR condition.

age ≥ 18 ?license ?Print can drivePrint cannot driveage ≥ 18 ANDlicense ?Print can drivePrint cannot driveYYNNYN=
Figure 1.4.14: Two drawings of an AND condition. On the left two separate decisions are connected one after the other; the No exit of the first decision goes straight to "cannot drive". On the right the two conditions are written in a single decision box as "age ≥ 18 AND license ?". The two drawings give the same result.

Figure 1.4.14 draws the AND condition in two ways. In the drawing on the left, "age ≥ 18 ?" is asked first. If the answer is No, there is no need to check whether there is a license; the person cannot drive anyway, and the No exit of the first decision goes straight to the "Print cannot drive" box. If the answer is Yes, "license ?" is asked in the second decision. The drawing on the right fits the same logic into a single decision box. In an OR condition the situation reverses: when drawn with two decisions, the Yes exit of the first decision goes straight to the result, because it is enough for one of the conditions to be true.

In Java AND is written with && and OR with ||: if (age >= 18 && license). Here license is a boolean variable. Table 1.4.6 gives the possible cases for both conditions; the table was produced with a Java program.

Table 1.4.6: Truth table of the AND and OR conditions. The note in parentheses shows the cases where Java does not look at the second condition at all.
agelicenseage >= 18age >= 18 && licenseage >= 18 || license
20yestruetruetrue (license not looked at)
20notruefalsetrue (license not looked at)
16yesfalsefalse (license not looked at)true
16nofalsefalse (license not looked at)false
Definition 1.4.5

Short-circuit evaluation is not evaluating the right side at all once the result is determined by the left side of the && and || operators. In A && B, if A is false the result is false and B is not looked at. In A || B, if A is true the result is true and B is not looked at.

Short-circuiting is the Java counterpart of the diagram drawn with two decisions. In the diagram the No exit of the first decision skipped the second decision; Java too looks at the second condition only if necessary. This behavior can be seen with an experiment. If the right-hand condition is written as a method that increments a counter each time it is called, then for age = 16 the expression age >= 18 && hasLicense(true) gives false and the counter stays at 0; the method was never called. For age = 20 the expression age >= 18 || hasLicense(false) gives true and the counter is again 0.

Short-circuiting has a practical use: the condition on the left can guarantee that the one on the right can be computed safely. In the expression count != 0 && total / count > 2, if count is 0 the division is never done. Had the order been reversed, that is, the division put on the left, the program would stop with an ArithmeticException for count = 0.

1.4.6Repetitive flow

One of the properties that makes a computer powerful is that it can do the same job thousands of times without tiring. Repetitive flow is the kind of flow in which operations are repeated many times. In a diagram, repetition is shown by an arrow going backward. This arrow returns to the top of a decision box; the decision box decides when the repetition ends.

1.4.6.1Kinds of loops

? i=1..1010 times ?∞
Figure 1.4.15: Icons of the three kinds of loop. (a) A condition-controlled loop. (b) Repetition a fixed number of times. (c) An infinite loop.

A condition-controlled loop repeats as long as a condition holds. How many times it will run may not be known in advance. "Read numbers until the user enters 0" is such a loop; how many numbers the user will enter is not known when the program is written. In Java this kind of loop is usually written with while.

In a loop that repeats a fixed number of times, the number of repetitions is known from the start. The job "print the numbers from 1 to 10" takes exactly 10 iterations. In Java this kind of loop is usually written with for. The choice between for and while is a matter of readability, not a necessity; every for loop can be written with while and every while loop with for.

In an infinite loop the condition always holds, so the operations repeat without stopping. An infinite loop is usually a bug. Forgetting to update the loop variable, setting up the condition wrongly or attaching the back arrow to the wrong place produces an infinite loop. Some programs, however, deliberately run with an infinite loop. A web server waits for incoming requests until it is shut down; the main loop of an embedded system turns as long as the device stays on. In Java this kind of loop is written while (true).

Loops give a program three things. A loop is efficient: the same operation is done as many times as needed without writing the code over and over. A loop is dynamic: the number of repetitions can vary with the input and the program adapts to different situations. A loop avoids code repetition: to print 1000 numbers, 3–4 lines are enough, not 1000.

Every loop has three parts. The initialization gives the loop variable its first value and runs only once. The condition is tested before every iteration and decides whether the loop goes on. The update changes the loop variable and runs at the end of each iteration. If one of these three parts is missing or wrong, the loop either never runs, runs too few or too many times, or never ends.

1.4.6.2Printing the numbers from 1 to 10

The first example of repetitive flow is printing the numbers from 1 to 10 on the screen. The algorithm has seven steps:

  1. Start.
  2. count = 1.
  3. If count ≤ 10 go to 4, otherwise go to 7.
  4. Write count.
  5. Increase count by 1.
  6. Go to 3.
  7. End.
Startcount = 1counter ≤ 10 ?Print countcount += 1EndYN
Figure 1.4.16: The diagram that prints the numbers from 1 to 10. The arrow leaving the "count += 1" box goes left, then up and returns to the top of the decision box. The No exit of the decision box is the loop's only exit door.

The "go to 3" in step 6 of the algorithm is, in the diagram, the back arrow returning to the top of the decision box. This arrow forms the loop. The decision box is the exit door of the loop: the moment the counter exceeds 10, the flow goes from the No exit to End. Note that the back arrow is attached to the decision box, below the "count = 1" box. The initial value is given only once, before the loop.

The Java counterpart of the diagram is a while loop:

public class OneToTen {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 10) {
            System.out.print(count + " ");
            count += 1;
        }
    }
}

Line 3 is the initialization: count gets the value 1. The while (count <= 10) on line 4 is the decision box. As long as the condition is true, the body between the curly braces runs. Line 5 writes the counter; since print adds no line end, the numbers appear on the same line, one space apart. Line 6 is the update: count += 1, that is, count = count + 1. When the body ends, execution goes back to line 4, to the condition. This return is the back arrow in the diagram; in Java no separate "go to" statement is written, and the closing curly brace of the while does this job.

Table 1.4.7 is the trace of the loop. The 4th–8th iterations in the middle of the table are abbreviated because they follow the same pattern.

Table 1.4.7: Trace of the OneToTen program. The last row is the test in which the condition is false and the loop is left.
Iterationcount (start of iteration)ConditionPrintedcount (end of iteration)Output
111 <= 10 → true121
222 <= 10 → true231 2
333 <= 10 → true341 2 3
………………
999 <= 10 → true9101 2 3 4 5 6 7 8 9
101010 <= 10 → true10111 2 3 4 5 6 7 8 9 10
—1111 <= 10 → false—111 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 

Two important numbers can be read from the table. The body has run 10 times; one number was printed in each iteration. The condition, however, was tested 11 times: ten times it came out true and the last time false. The condition being tested one more time than the body is a property of every loop with the decision box at the start. When the loop is left, count is 11, not 10. Because after 10 was printed the counter was increased once more, and then the condition came out false.

1.4.6.3Boundary condition: < or ≤?

A single character in the loop condition changes the number of repetitions. If the counter starts at 1 and goes up by 1 each iteration, four different forms of the condition give the results in Table 1.4.8.

Table 1.4.8: Number of times the body runs depending on how the condition is written, when the counter starts at 1 and goes up by 1 (measured with Java).
ConditionBodyCondition testscount at exitLast printed
count < 10910109
count <= 1010111110
count < 1110111110
count <= 1111121211

The condition count < 10 does not print 10, because when the counter is 10, 10 < 10 is false. The body runs 9 times and the numbers from 1 to 9 are printed. The conditions count <= 10 and count < 11 mean the same; both run 10 iterations and print 10 too. count <= 11 runs one iteration too many and prints 11 as well.

Definition 1.4.6

An off-by-one error is a loop running one iteration too few or one too many because its boundary condition was written wrongly.

This mistake is one of the most common in programming and the compiler does not catch it, because the wrongly written condition is also a valid Java expression. There is a simple way to prevent the mistake: test the condition with the last value. "From 1 to 10" includes 10. So the condition must be true when the counter is 10. 10 < 10 is false and 10 <= 10 is true; the right condition is count <= 10. The same check is made with the first value: the condition must be true when the counter is 1, otherwise the loop never starts.

1.4.6.4The loop symbol and for

The same problem, printing the numbers from 1 to 10, can be drawn more briefly with the special hexagon symbol for loops. The algorithm shrinks to three steps:

  1. Start.
  2. Loop: from 1 to 10.
  3. Write the loop variable.
  4. End of loop.
  5. End.
Starti = 1; i ≤ 10; i++Print iiEndrepeatdone
Figure 1.4.17: Printing 1 to 10 with the loop symbol. The hexagon gathers the initialization, the condition and the update in a single box. The small circle with "i" in it is the end of the loop: from there the flow returns to the hexagon along the "repeat" arrow, and when the loop is done it moves on to End along the "done" arrow.

The hexagon symbol gathers the three parts of the loop in a single box. The initialization is i = 1 and runs once. The condition is i ≤ 10 and is tested before every iteration. The update is i++, that is, it increases i by 1 and runs after every iteration. The small circle with "i" in it is the end of the loop. When the body ends, the flow returns from this circle to the hexagon; the hexagon does the update and tests the condition again. When the condition is false, the flow passes to End along the "done" arrow below the circle.

The Java counterpart of the hexagon is the for statement. The three parts are written in the same order inside the parentheses of for, separated by semicolons:

public class ForOneToTen {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}

This program and the while version give the same output: 1 2 3 4 5 6 7 8 9 10. The difference is only in the notation. Since for gathers the three parts of the loop in one line, the reader sees the number of repetitions at a glance. In the while version the initialization is written before the loop and the update at the end of the body, and they can be overlooked.

There is one more small but important difference between for and while. The variable int i declared in the initialization part of for is valid only inside the loop. If you try to use i after the loop, the compiler gives a cannot find symbol error. In the while version, since count was declared before the loop, it can be used after the loop too, and its value is 11.

1.4.6.5A decision inside a loop: counter and accumulator

The body of a loop can contain any kind of step, a decision box included. The example problem is this: the grades of five students are read; how many students passed (grade ≥ 50) and the class average are written.

Startpassed = 0sum = 0k = 1; k ≤ 5; k++Read gradesum += gradegrade ≥ 50 ?passed += 1kPrint passed, sum / 5EndYNrepeatdone
Figure 1.4.18: A decision inside a loop. The loop symbol runs for k = 1 to 5. In each iteration a grade is read and added to the sum. The Yes branch of the decision box increases the counter (passed) by 1; the No branch skips the counter and goes to the end of the loop.
int passed = 0, sum = 0;
for (int k = 1; k <= 5; k++) {
  int grade = scanner.nextInt();
  sum += grade;
  if (grade >= 50) {
    passed++;
  }
}
System.out.println(passed + " passed, average "
    + sum / 5.0);

This program uses two important loop patterns together.

Definition 1.4.7

A counter is a variable that increases by 1 when a condition holds and so counts how many times an event happens. An accumulator is a variable that gathers a result by adding a value in each iteration of the loop. Both get an initial value before the loop.

In the program passed is a counter: it increases by 1 with passed++ only when grade >= 50 is true. sum is an accumulator: whatever the condition, the grade read is added to it in every iteration. The initial value of both is 0; adding and counting start from zero. The decision box is inside the loop and is tested again in each iteration with the newly read grade. Table 1.4.9 is the trace of the program with the inputs 45, 70, 50, 30 and 88.

Table 1.4.9: Trace of the counter and the accumulator. Each row shows the state at the end of one iteration.
kgradesumDecisionpassed
1454545 >= 50 → false0
27011570 >= 50 → true1
35016550 >= 50 → true2
43019530 >= 50 → false2
58828388 >= 50 → true3

When the loop ends, passed = 3 and sum = 283. The program prints:

3 passed, average 56.6

Two Java details are hidden in this short program. The first is the grade on the boundary. A student with 50 passes, because the condition is written with >=. Had the condition been written grade > 50, the student with 50 would have failed and the result would be 2, not 3. The boundary value changes the condition by a single character; this is the form the off-by-one error takes in a decision box.

The second is the division. In the expression sum / 5.0, since the divisor is a decimal number, Java makes the division a decimal one: 283 / 5.0 = 56.6. Had the divisor been written 5, two integers would be divided. In Java the quotient of two integers is again an integer; the fractional part is discarded and 283 / 5 = 56. The expression "sum / 5" in the diagram does not show this distinction; when translating into Java, attention must be paid to the types. Note also that the decimal separator appears on screen as a point (56.6); println always writes numbers with a point.

Besides the counter and the accumulator there is a third pattern: the flag. A flag is a boolean variable that records whether an event has happened. It is false at the start; when the event takes place it is made true, for example found = true. After the loop ends, the flag shows whether the event happened at least once.

1.4.6.6A loop with a sentinel value

In the previous example the number of grades was known from the start: five. Often, however, it is not known beforehand how many values will come. A teacher sometimes enters 3 grades, sometimes 40. In this case the user announces the end of the input with a special value.

Definition 1.4.8

A sentinel value is a special value that announces the end of the input and is not counted as data. A value like 0, −1 or "end" is chosen.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN
Figure 1.4.19: A loop with a sentinel value. The first number is read before the loop. At the end of the body the next number is read and the back arrow returns to the decision. The decision "count > 0 ?" after the loop separates the case where no number was entered.
int sum = 0, count = 0;
int num = scanner.nextInt();
while (num != 0) {
  sum += num;
  count++;
  num = scanner.nextInt();
}
if (count > 0) {
  System.out.println("Average: "
      + (double) sum / count);
} else {
  System.out.println("No numbers");
}

Since it is not known how many values will come, the loop is condition-controlled and is written with while. The most important feature of the diagram is the read-first arrangement. The first value is read before the loop, on line 2. The next value is read at the end of the body, on line 6. In this way every value read is tested in the condition before entering the body. When the sentinel arrives, the condition is false at once and the sentinel never takes part in the sum.

Table 1.4.10 is the trace of the program with the input 12, 7, 5, 0. In each iteration row, the num column shows the value added to the sum in that iteration and the new value read at the end of the body.

Table 1.4.10: Trace of the sentinel loop with the input 12, 7, 5, 0. 0 is the sentinel and does not take part in the sum.
StepnumConditionsumcount
read first12—00
iteration 112 → 712 != 0 → true121
iteration 27 → 57 != 0 → true192
iteration 35 → 05 != 0 → true243
decision00 != 0 → false243

When the loop is left, sum = 24 and count = 3. The decision after the loop tests the condition count > 0; the condition is true and the average is printed:

Average: 8.0

Note the expression (double) sum / count in the average computation. (double) is a cast: it converts sum to a floating-point number before the division. In this way the division becomes a decimal one and 24 / 3 = 8.0. Had the cast not been written, two integers would be divided; for 24 / 3 the result would still be 8, but for 25 / 3 it would be 8 instead of 8.33….

A sentinel value must be a value that cannot appear in the real data. For student grades, −1 is a suitable sentinel; 0 is not, because a student may have scored 0 on the exam. If ordinary integers are being read, as in this example, 0 can be chosen as the sentinel, but then 0 can never be entered as data.

The count > 0 check after the loop is not unnecessary. If the user enters 0 as the first number, the loop never runs; sum and count stay at 0. Without the check, 0 / 0 would be computed. In Java the result of this division depends on the type. (double) 0 / 0 gives no error; it produces the value NaN (Not a Number) and Average: NaN would be printed on screen. With integers, however, 0 / 0 stops the program with java.lang.ArithmeticException: / by zero. Thanks to the check, the program prints No numbers in this case.

Common mistake

If the reading is put only at the start of the body, that is, "reading inside the loop" instead of "read first", the sentinel is added to the sum too. If the sentinel is 0, the sum does not change but count is counted one too many and the average comes out wrong. If the sentinel is −1, both the sum and the count are wrong. This is why the read-first arrangement exists: every value is tested before it is used.

1.4.6.7Leaving a loop early

In a search, once the thing sought is found the remaining iterations are unnecessary. The example problem is this: five numbers are read in order; the position at which the first negative number was entered is written. Once a negative number is found there is no point in reading the remaining numbers.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreak
Figure 1.4.20: Leaving a loop early. The loop has two exits: the No exit of the "i ≤ 5 ?" decision (what was sought was not found) and the Yes branch of the "x < 0 ?" decision (what was sought was found, break). The two paths join at the "Print pos" box.

In the diagram there is a second decision inside the loop: "x < 0 ?". The Yes branch of this decision takes the flow straight out of the loop after the assignment pos = i. So the loop has two exits. The first is the usual exit: when i passes 5 the condition becomes false; this means no negative number was found. The second is the early exit: when a negative number is found, the loop ends at once. The two paths join at the "Print pos" box. In Java the second exit is written with the break statement:

int pos = 0;
for (int i = 1; i <= 5; i++) {
  int x = scanner.nextInt();
  if (x < 0) {
    pos = i;
    break;
  }
}
System.out.println("Position: " + pos);

break ends only the loop it is in. Execution continues with the first statement after the loop, here println. The initial value of the pos variable is 0 and means "not found". Since positions start from 1, 0 is never confused with a real position. Table 1.4.11 is the trace of the program with the input 4, 9, −2, 6, 1.

Table 1.4.11: Trace of the search with break with the input 4, 9, −2, 6, 1. The loop ends in the third iteration; 6 and 1 are never read.
iLoop conditionxInner decisionpos
11 <= 5 → true44 < 0 → false0
22 <= 5 → true99 < 0 → false0
33 <= 5 → true−2−2 < 0 → true; break3

In the third iteration x = -2 is read and -2 < 0 is true. pos = 3 and break runs. break also skips the update part of for (i++) and the condition; the loop ends at once. The program prints Position: 3. Had no negative number been entered, for example with the input 4, 9, 2, 6, 1, the loop would have run five iterations, left through the No exit of the condition when i = 6, and Position: 0 would have been printed.

This diagram is not structured: the loop block has two exits. The Böhm–Jacopini theorem says the same job can also be done with a single-exit structure. The structured counterpart uses a flag instead of break:

int pos = 0;
boolean found = false;
for (int i = 1; i <= 5 && !found; i++) {
  int x = scanner.nextInt();
  if (x < 0) {
    pos = i;
    found = true;
  }
}

Here found is a flag. It is made true when a negative number is found. The loop condition now has two parts: i <= 5 && !found. The ! operator means "not"; !found means "not yet found". When the flag becomes true, the condition becomes false and the loop ends by its usual exit. Table 1.4.12 is the trace of this version with the same input.

Table 1.4.12: Trace of the flag version with the same input. The loop's only exit is the condition becoming false.
iLoop conditionxfoundpos
11 <= 5 && !false → true4false0
22 <= 5 && !false → true9false0
33 <= 5 && !false → true−2true3
44 <= 5 && !true → false—true3

The two versions give the same result: Position: 3. The difference between them is in the value of i when the loop ends. In the break version the loop ends while i = 3. In the flag version, at the end of the third iteration i++ runs, i = 4, and the condition is false with this value. That is why in the flag version the position is read not from i but from pos. Which version to choose is a matter of style. In short loops break is readable; in long loops, having a single exit makes tracing easier.

1.4.6.8Nested loops

A loop's body can contain another loop. This structure is called a nested loop. In each iteration of the outer loop, the inner loop runs through all its iterations from start to end. The following program writes a small multiplication table:

for (int i = 1; i <= 2; i++) {
  for (int j = 1; j <= 3; j++) {
    System.out.print(i * j + " ");
  }
  System.out.println();
}
Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjGo to the next lineiEndrepeatrepeatdonedonei = 1
Figure 1.4.21: The diagram of a nested loop. The outer hexagon controls i, the inner hexagon j. The "j" circle of the inner loop returns to the inner hexagon, and the "i" circle of the outer loop to the outer hexagon. The "Go to the next line" box is outside the inner loop, inside the outer loop.

The outer loop runs two iterations, for i = 1 and 2. The inner loop runs three iterations in each outer iteration, for j = 1, 2, 3, and prints the value of i * j. When the inner loop ends, println() moves to the next line. Table 1.4.13 shows all the steps of the program.

Table 1.4.13: Trace of the nested loop. The inner loop starts again from j = 1 in every outer iteration.
ijConditionPrinted
111 <= 3 → true1 × 1 = 1
122 <= 3 → true1 × 2 = 2
133 <= 3 → true1 × 3 = 3
144 <= 3 → false: println()(next line)
211 <= 3 → true2 × 1 = 2
222 <= 3 → true2 × 2 = 4
233 <= 3 → true2 × 3 = 6
244 <= 3 → false: println()(next line)
3—3 <= 2 → false: the outer loop ends—
1 2 3 
2 4 6 

The point to note in the table is that in the second outer iteration j starts again from 1. The reason is that the initialization int j = 1 is part of the inner for. Since the inner for statement runs from the beginning in every iteration of the outer loop, the initialization is done again each time. In the diagram this is shown by the flow entering the inner hexagon again from the top in every iteration of the outer loop.

The numbers of runs are found by multiplication. The inner body, that is, print, runs 2 × 3 = 6 times. println(), since it is part of the outer body, runs only 2 times. In general, if the outer loop runs m iterations and the inner n, the inner body runs m × n times. That is why nested loops slow down quickly on large inputs: a nested loop of 1000 × 1000 runs a million times.

1.4.7Subprograms

As diagrams grow they no longer fit on one page and become hard to read. Some sequences of steps are also needed again and again in different places of the diagram. The solution to both problems is the same: the diagram is divided into meaningful parts.

1.4.7.1The subprogram symbol and the method

Definition 1.4.9

A subprogram (predefined process) is a sequence of steps drawn as a separate diagram and called from the main diagram with the subprogram symbol. Its counterpart in Java is the method.

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYN
Figure 1.4.22: A subprogram. On the left the main diagram, on the right the subprogram "average(mid, fin)". The box with double side lines in the main diagram calls the subprogram. Dashed arrows show the flow passing to the subprogram and returning from the "Return avg" box to just after the call.

Figure 1.4.22 splits the diagram that computes a student's course average into two parts. The part on the right is the subprogram. In place of the Start box, the name and inputs of the subprogram are written: "average(mid, fin)". These inputs are called parameters. The subprogram adds 40% of the midterm grade and 60% of the final grade. At the end, instead of End there is a Return box: "Return avg". The Return box gives the computed value back to the place that called the subprogram.

The main diagram on the left first reads the midterm and final grades. Then it calls the subprogram with the subprogram symbol with double side lines: "avg = average(mid, fin)". At the moment of the call the flow passes to the subprogram. When the subprogram reaches the Return box, the result is given to the caller and the flow continues from just after the call. The main diagram assigns this result to the variable avg and, with the decision "avg ≥ 50 ?", writes whether the student passed.

A subprogram has three benefits. The same steps are not redrawn every time they are needed; they are drawn once and called many times. Each part can be tested separately; if the average computation is correct, only the reading and the decision need to be checked in the main diagram. The main diagram stays short and readable; the reader sees what the program does without going into detail.

The Java counterpart is as follows:

static double average(int mid, int fin) {
  double avg = mid * 0.4 + fin * 0.6;
  return avg;
}
public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  int mid = scanner.nextInt();
  int fin = scanner.nextInt();
  double avg = average(mid, fin);
  if (avg >= 50) System.out.println(avg + " passed");
  else System.out.println(avg + " failed");
}

Lines 1–4 are the subprogram. The header static double average(int mid, int fin) gives the name of the method (average), its two int parameters and the type of the value it returns (double). The statement return avg; is the Return box in the diagram. The expression average(mid, fin) on line 9 is the subprogram symbol; it is the call.

fin was chosen as the parameter name rather than final. The reason is that final is a reserved keyword in Java and cannot be used as a variable name. If int final = 70; is written, the compiler gives a series of errors, beginning with error: not a statement. In the diagram it is fine to write "final", but when translating into Java, keywords cannot be variable names.

1.4.7.2Tracing a subprogram call

When the user enters 40 and 70 on the same line, the program runs in the following steps.

  1. The program starts from main. Lines 7 and 8 read the two grades: mid = 40, fin = 70.
  2. On line 9 average is called. The values 40 and 70 are copied into the parameters of the method. The method's variables mid and fin are separate from the variables of the same name in main; only their values are the same.
  3. The subprogram's own diagram runs: avg = 40 × 0.4 + 70 × 0.6 = 16 + 42 = 58.0. This avg is the method's local variable; it is separate from the avg in main.
  4. return avg; runs: the value 58.0 is given to the caller. The memory area reserved for the method, the method's frame, is removed from the call stack; the method's local variables disappear with it.
  5. The flow continues from line 9: the returned value is assigned to avg in main.
  6. The decision on line 10: 58.0 >= 50 is true; the Yes branch prints 58.0 passed.
  7. main ends (End).
StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYNavg = 16 + 42 = 58.0
Figure 1.4.23: The moment the subprogram runs. In the main diagram the call box waits; in the subprogram the box "avg = mid × 0.4 + fin × 0.6" runs and 16 + 42 = 58.0 is computed.

The same subprogram can be called again with other inputs. Table 1.4.14 compares two runs. In the second run 45 and 30 are entered; the average comes out as 36.0 and the student fails.

Table 1.4.14: Two calls of the subprogram (run with Java).
midfinOperation in the subprogramValue returnedDecisionOutput
407040 × 0,4 + 70 × 0,6 = 16,0 + 42,058,058.0 >= 50 → true58.0 passed
453045 × 0,4 + 30 × 0,6 = 18,0 + 18,036,036.0 >= 50 → false36.0 failed

Note that in the output the average is written as 58.0, with .0 at the end. Since the method returns a double, Java writes the number in decimal form; it shows the decimal part even if the value is whole. In the product 40 * 0.4, since an int value is multiplied by a double value, the result is a double as well.

1.4.8Implementation and testing

After a diagram or program is written, one has to make sure it works correctly. There are two ways: tracing the diagram or program by hand on paper, and trying it with well-chosen inputs.

1.4.8.1The sum from 1 to n

The problem is to find the sum 1 + 2 + … + n for a number n entered by the user. In this problem all three kinds of flow come together: reading n and the initial values are sequential, the summing is repetitive, and writing the result is sequential again.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYN
Figure 1.4.24: The sum from 1 to n. "sum = 0, i = 1" is the initialization. While the decision "i ≤ n ?" is Yes, the box "sum += i, i += 1" runs and the back arrow returns to the decision. From the No exit the sum is printed.
System.out.print("n: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;
while (i <= n) {
    sum += i;
    i += 1;
}
System.out.println("Sum: " + sum);

sum is an accumulator: it starts at 0 and grows by the current i in each iteration. i is a counter: it starts at 1 and increases by 1 in each iteration. Table 1.4.15 is the run in which the user enters 4.

Table 1.4.15: Trace of the sum from 1 to n for n = 4.
StepCondition and operationsumi
start—01
iteration 11 <= 4 → true; 0 + 1 = 112
iteration 22 <= 4 → true; 1 + 2 = 333
iteration 33 <= 4 → true; 3 + 3 = 664
iteration 44 <= 4 → true; 6 + 4 = 10105
decision5 <= 4 → false105

The body runs 4 times, the condition 5 times. The program prints Sum: 10; 1 + 2 + 3 + 4 = 10. For n = 5 the same diagram runs one more iteration and prints Sum: 15. This result can also be checked with Gauss's formula: the sum from 1 to n is n(n + 1)/2. For n = 4 one gets 4 · 5 / 2 = 10, for n = 5, 5 · 6 / 2 = 15.

The initial value of the accumulator directly affects the result. If the box "sum = 0" is mistakenly written "sum = 1", the loop still adds 1 + 2 + 3 + 4 = 10, but since the start was 1 the result comes out as 11. For addition the accumulator starts at 0, for multiplication at 1. For example, when computing n!, the product starts with f = 1; had it started with f = 0, every product would be 0. The compiler does not catch such logic errors.

1.4.8.2Desk check and the trace table

Definition 1.4.10

A desk check is tracing a diagram or code on paper with an input, without using a computer. A trace table is the table that shows the values of the variables at each step of this trace: a column is set aside for each variable and a row for each iteration.

As an example, take a small program that adds the digits of a number. The digits of 472 are 4, 7 and 2; their sum is 13.

num = 472sum = 0num > 0 ?sum += num mod 10num = num / 10Print sumYN
Figure 1.4.25: The digit-sum diagram. In each iteration the last digit (num mod 10) is added to the sum, and the number is divided by 10 to drop its last digit.
int num = 472, sum = 0;
while (num > 0) {
  sum += num % 10;
  num /= 10;
}
System.out.println(sum);

The program rests on two integer operations. num % 10 gives the last digit of the number: 472 % 10 = 2. num / 10 is integer division and drops the last digit: 472 / 10 = 47. The digits are taken in this way from right to left, one at a time. sum += num % 10 is the short form of sum = sum + num % 10; num /= 10 likewise means num = num / 10. Table 1.4.16 is the trace table of the desk check.

Table 1.4.16: Trace table of the digit sum for 472. The condition column is the next test made with the value in that row.
Stepnum % 10sumnumCondition
start—0472472 > 0 → true
iteration 1224747 > 0 → true
iteration 27944 > 0 → true
iteration 341300 > 0 → false

The table also shows how many times the loop runs: 3 iterations and 4 tests. The program prints 13. The real value of the table is that it shows mistakes without running the program. If the box "num = num / 10" had been forgotten, the num column would stay 472 in every row. The condition would always be true and sum would grow by 2 each iteration: 2, 4, 6, … This oddity is seen at once in the second row of the table: the loop is never going to end. Had the program been run, this mistake would have been noticed only when the screen froze.

A few habits help when building a trace table. A column is set aside for every variable; a separate column is opened for the condition too. When a variable changes, the new value is written on a new row and the old one is not erased; this way the history of the change is visible. When the loop ends, the final values of the variables are noted separately; the steps after the loop use these values.

1.4.8.3Test cases

A diagram working correctly with a single input does not show that it will work correctly with every input. If the nested decision diagram is tried with the input 5, only the "positive" branch runs; it is not known whether the other two branches are right. That is why inputs are chosen deliberately.

Definition 1.4.11

Path coverage is running every exit of every decision box at least once in testing. Boundary values are the values immediately on both sides of the point where the result of the condition changes.

Table 1.4.17 shows test cases chosen for the positive/negative/zero diagram. Next to each input, the reason it was chosen and the expected output are written.

Table 1.4.17: Test cases for the positive/negative/zero diagram. All expected outputs were verified with the Java program.
InputWhy chosen?Expected
5Yes path of decision 1positive
−2Yes path of decision 2negative
0No path of both decisionszero
1 and −1both sides of the boundarypositive, negative

The first three inputs give path coverage: each of the three Print boxes runs once. The 1 and −1 in the last row are boundary values. Had the condition been mistakenly written num >= 0 instead of num > 0, 5 and −2 would still have given the right result; the mistake would have shown only when 0 was entered and "positive" was printed. Off-by-one mistakes show up exactly at boundary values. For a condition such as grade >= 50 the boundary values are 49 and 50.

For loops there is a separate rule: they are tried with inputs for which the loop runs zero times, once, and many times. Table 1.4.18 gives these cases for the sum-from-1-to-n diagram.

Table 1.4.18: Test cases for the sum-from-1-to-n diagram (run with Java).
nWhy chosen?Expected
0the body never runsSum: 0
1a single iterationSum: 1
4the ordinary caseSum: 10
−3invalid inputSum: 0 (is this what is wanted?)

For n = 0, 1 <= 0 is false and the body never runs; the program prints Sum: 0. This is a correct result: no numbers were added. The same happens for n = −3. But here the result is debatable. A negative n is a meaningless input; instead of printing 0, it might be better for the program to give a warning. The test case brings this question to light; the answer is given by the definition of the problem.

The last rule of testing is that the expected output is found by hand before the trial. First it is worked out that the result for n = 4 must be 10, then the program is run and compared with the actual output. Looking at the output after running the program and saying "it looks right" is the easiest way to overlook a mistake. If there is a difference, the mistake is in the diagram, in the code, or in the expectation itself.

1.4.8.4Ways of presenting an algorithm

A flowchart is not the only way to present an algorithm. Table 1.4.19 compares four notations on the odd/even example.

Table 1.4.19: Four ways of presenting an algorithm.
NotationThe odd/even exampleStrengthWeakness
Natural language"Read the number; if the remainder of dividing it by 2 is 0, write even, otherwise odd."Everyone can read itCan be ambiguous
FlowchartRead → Process → Decision → Print even / Print oddShows the flow visually; branching and loops are easy to seeClumsy for large problems
PseudocodeREAD num; IF num mod 2 = 0 THEN PRINT "even" ELSE PRINT "odd"Quick to write, close to codeNo standard syntax
Javaif (num % 2 == 0) … else …The computer can run itSyntax rules must be followed

Natural language is the easiest notation to read, but it is ambiguous. An expression like "if the number is large" may not say what it is larger than. Pseudocode stands between natural language and a programming language. Its keywords (READ, IF, THEN, PRINT) resemble a programming language, but it has no compiler and everyone uses their own form. Java is the most exact notation; the computer can run it. In return, all the rules, from semicolons to curly braces, must be followed. Within this range the flowchart stands out for its visuality: branches and loops are understood at once from the shape of the arrows.

In software engineering, today's counterpart of the flowchart is the UML (Unified Modeling Language) activity diagram. The idea is the same, the symbols are slightly different. The start is drawn with a filled circle, a decision again with a diamond, and activities with rounded boxes. In designing object-oriented programs, activity diagrams are used together with the other diagrams of UML.

1.4.8.5Drawing tools

A flowchart can be drawn with paper and pencil or on a computer. Table 1.4.20 summarizes the common tools.

Table 1.4.20: Flowchart drawing tools.
ToolWhat it doesNote
Paper and pencilThe fastest sketch; the only option in an examLaborious to correct
draw.io (diagrams.net)A free drawing tool that runs in the browser; ready-made flowchart symbolsDraws, does not run
Microsoft VisioA commercial diagramming program; standard symbol librariesPaid
FlowgorithmRuns the diagram and tracks variables; generates code in many languages, Java includedFree, for education
MermaidDraws a diagram from text; GitHub and many Markdown tools display it directlyStored together with the code

Mermaid takes an interesting approach: the diagram is not drawn but written. The Mermaid text of the odd/even diagram is as follows:

flowchart TD
  A([Start]) --> B[/Read num/]
  B --> C{num mod 2 = 0 ?}
  C -- Yes --> D[Print even]
  C -- No --> E[Print odd]
  D --> F([End])
  E --> F

The flowchart TD on the first line starts a flowchart; TD (top-down) means a top-to-bottom layout. Each node has a letter name and a text in square brackets. The form of the brackets determines the symbol: ([ ]) the Start/End oval, [/ /] the input parallelogram, { } the decision diamond, [ ] the process rectangle. --> is a flow line, -- Yes --> a labeled decision exit. The tool decides the position of the boxes on the page itself. The text form makes it easy to keep the diagram in the same files as the program code and to update it together with the code.

Whatever the drawing tool, the rules are the same: a single Start, labeled decision exits, non-crossing arrows. The tool only makes drawing easier; the correctness of the diagram still depends on the person who designs it.

1.4.9Common mistakes

Some mistakes are very common when drawing flowcharts and when translating a diagram into Java. The compiler catches some of them; others lead to programs that compile but run wrongly. The mistakes in the second group are more dangerous, because the program produces a wrong result without any warning.

Common mistake

A single exit on a decision box. Two arrows must leave a decision symbol, and both must be labeled Y/N. If only the Yes arrow is drawn, what happens in the "no" case remains unclear. Even if there is nothing to do on the No branch, the arrow is drawn and connected straight to the junction.

Common mistake

The wrong symbol. Using a rectangle for reading from the keyboard and a parallelogram for computation makes the diagram misleading. The rule is simple: input is a parallelogram, process a rectangle, a question a diamond.

Common mistake

Using = in a comparison. if (result = 0) does not compile: error: incompatible types: int cannot be converted to boolean. Comparison is written with ==: if (result == 0).

Common mistake

Forgetting the initial value. If there is no "count = 1" box in the diagram, Java also gives an error. If int count; is declared and while (count <= 10) is written without giving it a value, the compiler gives the message error: variable count might not have been initialized.

Common mistake

Forgetting the update. If there is no "count += 1" box, the counter never changes and the condition stays true: an infinite loop. The compiler does not catch this mistake; the program writes 1 on the screen without stopping.

Common mistake

A boundary error. For "from 1 to 10", writing count < 10 skips 10. The condition must be tested with the last value: when the counter is 10 the condition must be true.

Common mistake

A semicolon after the loop header. The line while (count <= 10); compiles, but the final semicolon is an empty statement and becomes the body of the loop. The block with curly braces below it is not part of the loop. Since the counter never increases, the condition stays true and the program hangs without printing anything. JDK 21 compiles this code without a warning.

Common mistake

Attaching the back arrow to the wrong place. In the diagram that writes 1 to 10, if the back arrow returns not to the decision box but to the top of the "count = 1" box, the counter becomes 1 again in every iteration. The condition stays true and 1 is written on the screen without stopping: again an infinite loop. The back arrow must return to the decision box, after the initial value. In Java this mistake corresponds to writing the initial assignment inside the loop.

Common mistake

Integer division. If the expression "sum / 5" in the diagram is written in Java between two ints, the decimal part is discarded: 283 / 5 = 56. For a decimal result, one of the operands must be a double: sum / 5.0 or (double) sum / count.

1.4.10Summary

  • An algorithm is the ordered, finite steps that solve a problem. A flowchart is the drawing of an algorithm with symbols and arrows; it is a plan independent of the programming language. It becomes clumsy in large programs; then pseudocode is more practical.
  • Basic symbols: oval Start/End, parallelogram input, rectangle process, diamond decision, hexagon loop, wavy box print, circle connector, arrow flow line. Additional symbols: subprogram, off-page connector, data store, manual input, comment, preparation.
  • Drawing rules: a single Start, at least one End; flow from top to bottom and left to right; only the decision box has two exits and the exits are labeled Y/N; lines do not cross.
  • Java counterparts: Start/End → main; input → nextInt(); process → assignment; decision → if/else; decision + back arrow → while; hexagon → for; print → println; subprogram → method. The "=" in a process box in the diagram is assignment (=), in a decision box it is comparison (==).
  • The Böhm–Jacopini theorem: every algorithm can be written with sequence, selection and repetition. In a structured diagram every structure has a single entry and a single exit. goto cannot be used in Java; break and continue are limited jumps that affect only the loop they are in.
  • In sequential flow every step runs exactly once; the order of dependent steps cannot be changed. Java catches the reading of a variable that has received no value at compile time.
  • In conditional flow P or Q runs according to the decision box K. Three or more possibilities are drawn with nested decisions (else if). In Java the result of the % operation takes the sign of the dividend: -3 % 2 == -1. AND is written && and OR ||, and they are evaluated with short-circuiting.
  • In repetitive flow the back arrow returns to the decision box. The three parts of a loop are the initialization, the condition and the update. If the decision comes first, the condition is tested one more time than the body runs (1 to 10: body 10 times, condition 11 times).
  • Loop patterns: a counter increases by 1 when a condition holds; an accumulator adds up a value in each iteration (starts at 0 for addition, 1 for multiplication); a flag records whether an event has happened. In a sentinel loop reading is done first; the sentinel does not take part in the sum; after the loop the case count = 0 is checked separately.
  • Early exit is written with break; its structured counterpart is widening the loop condition with a flag. In a nested loop the inner body runs m × n times.
  • A subprogram is a sequence of steps drawn and called separately; it takes parameters and returns a value with the Return box. In Java it is a method; parameters are copied, and local variables disappear when the call ends.
  • In a desk check a diagram or code is run on paper with a trace table. Test cases include every exit of every decision (path coverage) and the boundary values. Loops are tried with inputs that make them run zero times, once and many times; the expected output is found by hand before the trial.
  • Pitfalls: the < / ≤ boundary error; forgetting the update or attaching the back arrow to the initialization box (an infinite loop); a semicolon after the loop header; integer division.

1.4.11Key terms

The key terms of this chapter are listed below.

  • algorithm
  • flowchart
  • pseudocode
  • sequential flow
  • conditional flow
  • structured flowchart
  • nested decision
  • comparison operator
  • logical operator
  • short-circuit evaluation
  • loop
  • while loop
  • for loop
  • infinite loop
  • accumulator
  • sentinel value
  • break / continue
  • nested loop
  • subprogram (predefined process)
  • desk check
  • trace table
  • path coverage

1.4.12Test Yourself

  1. Which symbols are used to draw the steps "save the results to a file", "write the sum on the screen" and "i = 1; i ≤ 5; i++"?

    Answer

    Saving to a file is writing to a lasting place: the data store (cylinder). Writing to the screen is drawn with the Print symbol (the box with a wavy bottom edge); some sources use the output parallelogram too. The expression that contains the initialization, condition and update together is the loop symbol (hexagon); its Java counterpart is for (int i = 1; i <= 5; i++).

  2. After the fragment int x = 50, steps = 0; while (x > 1) { x = x / 2; steps++; } has run, what are x and steps?

    Answer

    With integer division x takes these values: 50 → 25 → 12 → 6 → 3 → 1. At each division steps increases by 1; 5 divisions are made. When x = 1, 1 > 1 is false and the loop ends. Result: x = 1, steps = 5. In the divisions 25 / 2 and 3 / 2 the decimal part is discarded.

  3. How many times does the loop for (int i = 3; i <= 15; i += 4) sum += i; run? If sum starts at 0, what is it at the end?

    Answer

    i takes the values 3, 7, 11 and 15; 15 also satisfies the condition because the condition is written with <=. The next value is 19 and 19 <= 15 is false. The loop runs 4 times; sum = 3 + 7 + 11 + 15 = 36. The condition is tested 5 times.

  4. The user enters 8, 0, 5, 0 in order into the average program whose sentinel value is 0. What does the program print? What happens to the value 5?

    Answer

    The first value read is 8; 8 != 0 is true, sum = 8, count = 1. At the end of the body 0 is read; 0 is the sentinel and the loop ends. Since count > 0 is true, Average: 8.0 is printed. 5 and the second 0 are never read; the program ends without waiting for them. The sentinel determines exactly where the input ends.

  5. The program that finds the position of the first negative number runs with the input 3, −1, −4, 2, 7. What do the break version and the flag version print? What is i in the two versions when the loop ends?

    Answer

    The second number −1 is negative; both versions print Position: 2. −4 is not considered at all, because what is sought is the first negative number. In the break version the loop ends while i = 2. In the flag version, i++ runs at the end of the second iteration; i = 3 and 3 <= 5 && !true comes out false. (For the comparison in the question, i is assumed to be declared before the loop.)

  6. The outer loop runs a from 1 to 3. The inner loop runs b from 1 to a and its body writes one *; after the inner loop println() runs. What is seen on the screen? How many stars are written?

    Answer

    The number of iterations of the inner loop depends on the outer variable: 1 for a = 1, 2 for a = 2, 3 for a = 3. Three lines are seen on the screen: *, **, ***. In total 1 + 2 + 3 = 6 stars are written. Here the number of runs of the inner body is not m × n but the sum of the iteration counts.

  7. For the job "write the multiples of 5 from 1 to 100", for (int i = 5; i < 100; i += 5) has been written. How many numbers are written? What is the mistake?

    Answer

    5, 10, …, 95 are written: 19 numbers. When i = 100, 100 < 100 is false and 100 is not written. This is an off-by-one mistake. If the condition is tested with the last value, the mistake shows: 100 is also a multiple, so the condition must be i <= 100. The corrected loop writes 20 numbers.

  8. In the odd/even program the condition has been written num % 2 == 1. What is written when −7 is entered? What would be written if the condition were num % 2 == 0?

    Answer

    In Java the remainder takes the sign of the dividend: -7 % 2 == -1. In the first condition -1 == 1 is false and −7 is taken to be "even"; this is wrong. In the second condition -1 == 0 is false, "odd" is written from the No branch; this is right. Testing evenness is safe with negative numbers too.

  9. Which inputs should be chosen at the least to test the diagram "if grade ≥ 50 write 'passed', otherwise 'failed'"? Why?

    Answer

    For path coverage both branches must run: two grades, one ≥ 50 and one < 50. For boundary values, the two sides of the point where the result of the condition changes are chosen: 49 (failed) and 50 (passed). These two inputs also cover both branches. The ends of the valid range (0 and 100) can be added too. If the condition was mistakenly written > 50, only the input 50 exposes the mistake.

1.4.13Further reading

  • P. Deitel and H. Deitel, Java: How to Program (11th ed., 2017), Chapters 4 and 5: presents Java's control statements together with UML activity diagrams; works through counters, sentinel values and nested control structures with many examples.
  • A. B. Downey and C. Mayfield, Think Java (2nd ed., 2019): offers a short, plain introduction to conditionals, loops and methods; the whole book can be read free on the authors' site.
  • C. Böhm and G. Jacopini, "Flow Diagrams, Turing Machines and Languages with Only Two Formation Rules" (1966): the original paper on the structured programming theorem; it proves that flowcharts can be reduced to three structures.
  • Oracle, The Java Tutorials, "Control Flow Statements": the official explanation and short examples of the if, switch, while, do-while, for, break and continue statements.

1.4.14References

  1. ISO 5807:1985, Information processing — Documentation symbols and conventions for data, program and system flowcharts, program network charts and system resources charts.
  2. C. Böhm, G. Jacopini, “Flow Diagrams, Turing Machines and Languages with Only Two Formation Rules”, Communications of the ACM 9(5), 1966.
  3. P. Deitel, H. Deitel, Java: How to Program, 11th ed., Pearson, 2017.
  4. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.
  5. Oracle, The Java Tutorials: “Control Flow Statements” (docs.oracle.com/javase/tutorial).
  6. K. Sierra, B. Bates, T. Gee, Head First Java, 3rd ed., O'Reilly, 2022.

Related pages: Chapter 1.4 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.