Computer Fundamentals and Introduction to Programming · Lecture Notes

Chapter 4.2: Flowcharts

When an algorithm is first put on paper, a drawing often comes before any text. Boxes show the steps and arrows show their order. Such a drawing is called a flowchart. This chapter introduces the symbols used in flowcharts and the rules of a good diagram. Then come the three kinds of flow that are the building blocks of every algorithm. In sequential flow, steps run one after another. In conditional flow, the path splits according to a question. In repetitive flow, a group of steps runs again and again. Each structure is executed step by step on small examples, and the value of each variable at each step is given in trace tables. Loop patterns such as the counter, the accumulator, and the sentinel value, as well as nested loops, early exit, and flags, are also treated separately. The last sections show how a flowchart is translated into Java code and which inputs a flowchart is tested with.

Learning outcomes

Symbols
Recognize the basic flowchart symbols (start/end, process, decision, input/output, arrow, connector) and the additional symbols; choose the right symbol for each step.
Flow
Establish the order of operations with arrows; apply the rules of a readable diagram; describe the same algorithm with a flowchart and with pseudocode.
Control
Show sequential, conditional, and repetitive flow in a diagram; use the patterns of decision chain, compound condition, counter, accumulator, sentinel value, nested loop, post-test loop, early exit, and flag; execute a diagram step by step with a trace table.
Translation
Translate a diagram into pseudocode and into a Java program; split a large diagram into subprocesses; test a diagram with normal and boundary inputs and with inputs on which the loop runs zero, one, and many times.

4.2.1The flowchart

An algorithm is a clear and finite sequence of steps for solving a problem. Steps can also be described in plain prose. But as the text grows longer, it becomes easy to lose track of which step comes after which, and under what conditions a step is skipped or repeated. A flowchart makes this order visible.

4.2.1.1What is a flowchart?

Definition 4.2.1

A flowchart is a drawing that shows the steps of an algorithm with standard symbols and the order in which they run with arrows. The shape of a symbol tells the kind of step (start, process, decision, input/output), the short expression inside tells what the step does, and the arrow tells which step execution moves to.

An everyday example makes the definition concrete. An apartment building has a keypad lock on its door. The small computer inside the lock does the same job each time: it reads the code entered, checks whether it is correct, opens the door if it is, and sounds a warning otherwise. Figure 4.2.1 shows this job as a flowchart.

YesNoStartread the codecorrect?open the doorsound warningEnd
Figure 4.2.1: Flowchart of the door-code algorithm. Two paths leave the decision box: if the code is correct, “open the door” runs; otherwise “sound warning” runs. The two paths join at the small circle below and reach End.

The diagram is read from top to bottom. Execution begins at the round-ended box labeled Start. An arrow carries execution to the “read the code” box. Next comes the diamond-shaped decision box. It contains a question: “correct?” Depending on the answer, one of two arrows is followed. The path along the Yes arrow opens the door; the path along the No arrow sounds a warning. Both paths finally meet at the same point and reach the End box.

This small drawing shows three basic properties of a flowchart. First, the kind of each step is clear from its shape; the reading step and the deciding step are in different boxes. Second, the order of the steps is fixed by the arrows; the reader does not have to guess which step comes first. Third, the paths leaving a decision box can be followed separately; on each run only one of these paths is used.

4.2.1.2Why draw a diagram?

A flowchart is independent of any programming language. The same diagram can be written in Java, Python, or C. That is why the logic of an algorithm can be discussed before it is decided which language it will be coded in. In a team, people who are not programmers, for example a laboratory manager or a business-process manager, can also read the diagram and ask “what happens in this case?”

The second benefit of drawing a diagram is that errors are seen early. If only one arrow leaves a decision box, nobody has thought about what happens in the other case. A box that no arrow enters never runs. If nothing changes along the path of a backward arrow, the loop goes on forever. Such gaps hide between the lines of code; in a diagram they are noticed from the shape of the drawing.

The third benefit is about learning. For a beginner, one of the hardest concepts is the order of execution. The computer runs lines one at a time and in sequence. It skips some lines according to a condition and repeats others. In a flowchart this order can be followed with a finger. Throughout this chapter, every diagram will be executed this way, box by box.

4.2.2Symbols

The symbols of flowcharts are defined by an international standard: ISO 5807. The standard was published in 1985, and most drawing tools in use today follow it. Five basic symbols are enough for a small algorithm. Additional symbols are used when a diagram grows or when external things such as files and reports are to be shown.

4.2.2.1Basic symbols

Start / EndBeginning / endEvery diagram has one Start and at least one Endsum = a + bProcessComputation, assignmenta > b ?DecisionTwo exits: Yes / Noread aInput / outputTaking data in (read), showing it (print)Flow lineDirection of execution; the arrowhead mattersAConnectorMerging paths / page jump
Figure 4.2.2: The basic flowchart symbols. Top row: start/end (oval), process (rectangle), and decision (diamond); bottom row: input/output (parallelogram), flow line (arrow), and connector (small circle).

Figure 4.2.2 shows the basic symbols together. The job of each is explained below.

Definition 4.2.2

The terminal symbol (start/end) is an oval or a rectangle with rounded ends. It shows where the algorithm begins and where it ends. Every diagram has a single Start and at least one End.

No arrow enters the Start symbol; only an arrow leaves it. An arrow enters the End symbol; none leaves it. A diagram may have more than one End. For example, in the number-guessing game the game ends immediately on a correct guess; in that case drawing a separate End after the text “You got it” simplifies the diagram. Even so, in most cases merging the paths and leading them to a single End makes reading easier.

Definition 4.2.3

The process symbol is a rectangle. It shows a computation or an assignment. An assignment gives a variable a new value: the expression sum = a + b computes the value a + b on the right and writes the result into the variable named sum.

The word variable appears here for the first time. A variable can be thought of as a box in memory that has a name. At any moment the box holds a single value. When a new value is written, the old one is erased. The equals sign in an assignment is different from equality in mathematics. i = i + 1 is meaningless in mathematics, because no number can equal one more than itself. In a flowchart and in a program, however, this statement means “add 1 to the current value of i and write the result back into i.” If i was 4 before, it is 5 after this box runs.

Definition 4.2.4

The decision symbol is a diamond. A question whose answer is “yes” or “no,” that is, a condition, is written inside it: a > b ?. One arrow enters the decision symbol and two leave it; the outgoing arrows are labeled Yes and No.

A condition is a comparison. In flowcharts and in Java there are six comparison operators. These are < (less than), <= (less than or equal), > (greater than), >= (greater than or equal), == (equal), and != (not equal). Two equals signs are used for the equality question, because the single equals sign is reserved for assignment. Some books also use the signs ≤, ≥, and ≠; the meaning is the same.

Definition 4.2.5

The input/output symbol is a parallelogram. It shows the algorithm taking data from outside (“read a”) or giving a result to the outside (“print sum”). Data taken from outside is called input, and the result given to the outside is called output.

The word “read” covers data coming from the keyboard, from a file, or from a sensor. A flowchart is not concerned with where the data comes from; it only says that at this point a value enters the algorithm. Likewise “print” covers writing to the screen, to a printer, or to a file.

Definition 4.2.6

The flow line, or simply arrow, joins two symbols and shows the direction of execution. The connector is a small circle; it shows the point where several paths meet, or that the diagram continues elsewhere.

The arrowhead matters. A line without a head says that two boxes are connected but not which runs first. That is why every flow line has an arrowhead at its end. The connector marks the place where two paths leaving a decision meet again, as in Figure 4.2.1. A connector with a letter inside is paired with another connector carrying the same letter. This way there is no need to draw a long arrow from one corner of the page to the other.

Table 4.2.1: The basic symbols, their jobs, and sample expressions that can be written inside them.
SymbolShapeJobExample
OvalBeginning or endStart
RectangleProcess (computation, assignment)sum = a + b
DiamondDecision (condition)a > b ?
ParallelogramInput / outputread a
ArrowDirection of executiongo to the next step

4.2.2.2What goes inside a symbol?

Because the shape of a symbol already tells the kind of step, only a short expression of that step is written inside. A decision symbol gets a question: a > b ?. A process symbol gets a command: sum = a + b. An input/output symbol gets what is read or printed: “read a,” “print sum.” This distinction lets the person reading a diagram know what will happen at a step even before reading the inside of the box.

The question form has one more rule: its answer must have two options. The question “which is larger, a or b?” has the answer “a” or “b,” but leaves the case of equality open. The question a > b ?, on the other hand, always has the answer yes or no: if a = b, the answer is no. That is why a comparison is always written in a decision box.

Example 4.2.1

An algorithm computes a student's average from the midterm and final exam grades and prints the pass/fail result. Its steps are: get the midterm grade; get the final grade; compute the average as midterm × 0.4 + final × 0.6; check whether the average is 50 or above; print the result on the screen. Which symbol does each step get, and what is written inside?

Solution. “Get the midterm grade” is an input: a parallelogram, with “read midterm” inside. The final grade likewise goes in a parallelogram. The average computation is an assignment: a rectangle, with avg = midterm × 0.4 + final × 0.6 inside. “Is it 50 or above” is a question: a diamond, with avg >= 50 ? inside. Printing the result is an output: one parallelogram on each of the Yes and No branches, with “print Pass” and “print Fail” inside. Start is added at the very beginning and End at the very end. If the midterm is 40 and the final is 60, the average is 40 × 0.4 + 60 × 0.6 = 16 + 36 = 52; since 52 ≥ 50, the Yes path is followed and “Pass” is printed.

Common mistake

Writing a computation in a parallelogram. sum = a + b has nothing to do with the screen or the keyboard; it computes a value in memory. It therefore belongs in the process symbol, the rectangle. The parallelogram is only for exchanging data with the outside world. A similar confusion appears when a command is written in a decision box: the sentence “compare a with b and print the larger” is not a question, and it does two jobs at once. The right way is to write a > b ? in the decision box and move the printing to parallelograms on the branches.

4.2.2.3Additional symbols

The five basic symbols are enough for small algorithms. In some cases the additional symbols of ISO 5807 are used. A large diagram may be split across several pages, a separately drawn subprocess may be called, or a file or report may need to be shown. Table 4.2.2 summarizes the six met most often.

Table 4.2.2: Additional symbols.
SymbolNameJobExample
Off-page connectorThe diagram continues on another page; the page and point are written inside.2-A
Predefined processCalls a separately drawn subprocess.Compute average
PreparationGives the start and limit of a loop counter in a single symbol.i = 1 → n
DocumentA printed output or report.Grade sheet
Data storeData kept on disk or in a database.Student records
AnnotationAttaches a note to a symbol with a dashed line; takes no part in the flow.grade 0–100

The off-page connector is a relative of the on-page connector. The label “2-A” inside it means “continues at point A on the second page.” The predefined process symbol is a rectangle with two vertical lines on its sides. This symbol is the tool for splitting large diagrams into parts: a subprocess is drawn once and called with this symbol wherever it is needed in the main diagram. The preparation symbol is a hexagon and gathers the start value, limit, and step of a counting loop in one box. The annotation symbol takes no part in the flow; it is joined to a box by a dashed line and gives information to the reader. For example, the annotation “grade 0–100” reminds the reader what range the input must be in.

4.2.3Diagram design

Knowing the symbols is not enough to draw a diagram. The path from a problem to a diagram has definite steps. When these steps are followed, no case is left out, and the result is a drawing that is easy to read.

4.2.3.1A diagram step by step: the larger of two numbers

The problem is short: two numbers are given and the larger one is to be printed. The diagram is built in five steps.

  1. Determine the input and output. What the algorithm takes from outside and what it gives to the outside is written first. The input is two numbers: a and b. The output is the larger number. Both are shown with parallelograms: “read a, b” and “print the larger.”
  2. Order the steps. Start and End are added. The steps are arranged from top to bottom: reading first, printing last. A value that has not been read cannot be compared; that is why the reading box is always above the decision.
  3. Separate the decisions. Which number is printed depends on a question: is a greater than b? The decision box a > b ? goes in between. The single “print the larger” box now splits into two boxes: “print a” and “print b.”
  4. Connect the arrows. Each box is joined to the next with an arrow. The two arrows leaving the decision are labeled Yes and No. The two branches merge at a connector below and go to End.
  5. Trace with an example. The diagram is executed by hand with an input. For a = 4, b = 9, 4 > 9 is false; the No path is followed, the “print b” box runs, and 9 is printed. The result is correct.
1. Determine input and output2. Order the steps3. Separate the decisions4. Connect the arrows5. Trace with an exampleStartread a, ba > b ?print aprint bEnd 1. Determine input and output2. Order the steps3. Separate the decisions4. Connect the arrows5. Trace with an exampleYesNoStartread a, ba > b ?print aprint bEnd
Figure 4.2.3: Building the diagram that finds the larger of two numbers. (a) Step 3: when the decision is added, the output splits into two boxes; the arrows are not there yet. (b) Step 5: the arrows are connected, and the path followed for a = 4, b = 9 is shown in color: the No path, “print b,” and 9.

The fifth step is often skipped, but it is the most valuable one. During a hand trace, trying a single input is not enough. The Yes path must also be tried with a = 9, b = 4; in that case 9 is printed. And what if a = b = 5? Since 5 > 5 is false, the No path is followed and b, that is 5, is printed. When the two numbers are equal it does not matter which one is printed; the diagram gives the correct result in this case too. This small experiment shows that the result would not change even if >= were written in the decision box instead of >.

4.2.3.2Readability rules

The same algorithm can be drawn well or badly. Figure 4.2.4 shows the same two-number problem in two ways. In the drawing on the left, the arrows cross each other, the exits of the decision box are unlabeled, and three separate jobs, such as “print b, end, a=b,” are crammed into one box. The drawing on the right flows from top to bottom, the exits of the decision are labeled, and each box contains a single job.

Starta > bprint b, end, a=bprint aEnd YesNoStarta > b ?print aprint bEnd
Figure 4.2.4: An unreadable and a readable diagram. On the left, crossing arrows, an unlabeled decision, and three operations in one box; on the right, top-to-bottom flow, a decision labeled Yes/No, and one operation per box.

The rules fall under three headings:

  • Direction of flow. The flow runs from top to bottom and from left to right as far as possible. The reader's eye moves in this direction; arrows going the other way are used only in loops, to show the return. Crossing arrows are kept to a minimum; if crossing is unavoidable, a connector is used.
  • Decision labels. Every arrow leaving a decision carries a meaningful label such as Yes/No (or True/False). In an unlabeled decision, which path is chosen in which case is left to guesswork.
  • One job per box. A single basic operation is written in a symbol. If three operations are crammed into one box, it becomes unclear which is done first, and if the box contains a decision, that decision is overlooked. If a diagram grows and no longer fits on the page, it is split into subprocesses.
Common mistake

Drawing only one arrow out of a decision. The student draws the case in mind, for example “if the grade is above 60, print Pass,” and forgets the other case. When the grade is 45, the diagram does not say where execution goes; the flow breaks. Two arrows always leave a decision box. If there is no job to do in the other case, the No arrow goes directly to the merge point.

4.2.3.3Flowchart and pseudocode

The second common way of describing an algorithm is pseudocode.

Definition 4.2.7

Pseudocode is a way of writing the steps of an algorithm in short sentences that resemble a programming language but are not bound by its rules. Lines are read in order; lines inside a decision or loop are shown by indentation.

Figure 4.2.5 shows the algorithm that finds the absolute value of a number in two forms. If the number is negative, its sign is changed; otherwise it stays as it is.

YesNoStartread xx < 0 ?x = −xprint xEnd
Figure 4.2.5: Flowchart of the absolute-value algorithm: x is read, if x < 0 then x = −x is done, then x is printed.
read x
if x < 0 then
    x = −x
print x

The two notations describe the same algorithm and either can be translated into the other line by line. “read x” corresponds to the parallelogram, “if x < 0 then” to the decision box, the indented line x = −x to the rectangle on the Yes branch of the decision, and “print x” to the last parallelogram. The No branch of the decision has no box; the arrow goes straight to the printing box. In pseudocode this case is shown by a single indented line under the “if” line.

Table 4.2.3: Comparison of the flowchart and pseudocode.
The flowchartPseudocode
ShapeSymbols and arrowsShort indented sentences
StrengthBranching and looping are visible at a glanceQuick to write, very close to code
WeaknessDoes not fit on a page when it grows; hard to changeThe structure of the flow depends on indentation
Best suited forLearning, presentations, business processesLong algorithms, right before coding

Pseudocode has no standard. Some books write “if … then,” others “when … do”; some use = for assignment, others ←. What matters is that each step is clear. In this chapter, pseudocode is written with English words and Java-like symbols: assignment =, equality question ==, remainder %.

4.2.3.4The three structures of structured programming

In a flowchart, arrows can be drawn anywhere. An arrow jumping to a random box in the middle of the diagram is technically possible. In the 1960s, as programs grew, this freedom caused serious problems. The arrows tangled, and it was impossible to follow by how many different paths a box could be reached. Such drawings and programs were called spaghetti code, after a tangle of pasta.

The solution is to use only three patterns instead of drawing arrows at random. Figure 4.2.6 shows these three patterns.

SequenceProcess AProcess BSelectioncondition ?ABYesNoRepetitioncondition ?bodyYesNo
Figure 4.2.6: The three structures of structured programming. Sequence: process A, then process B. Selection: A or B according to the condition. Repetition: the body runs again as long as the condition is true. Each structure has a single entry and a single exit.
Definition 4.2.8

Structured programming is the approach of building algorithms from only three control structures. The sequence structure: steps run one after another. The selection, or decision, structure: one of two paths runs according to a condition. The repetition, or loop, structure: a group of steps runs again as long as a condition is true.

Theorem 4.2.1 (Böhm–Jacopini)

Every algorithm can be written with only the structures of sequence, selection, and repetition. Corrado Böhm and Giuseppe Jacopini published this result in 1966.

What the theorem says is strong: arrows that jump at random are never needed. Every diagram drawn in spaghetti form has a structured equivalent that does the same job. If necessary, one or two extra variables (for example a flag) are used.

The common property of the three structures is the single entry, single exit rule. One arrow enters each structure from above and one arrow leaves from below. Thanks to this, a structure can be put in place of any box inside another structure. For example, a whole decision structure can be placed instead of the rectangle in the body of a loop. These are called nested structures. Large algorithms are built this way, by nesting small structures. Any part of the diagram can be understood and tested separately through its own entry and exit arrows.

Programming languages adopted this idea too. In older languages the goto statement, which jumps to any line of the program, was common. In Java, goto is a reserved word, that is, it cannot be used as a variable name, but it does nothing in the language. In Java, the flow of execution is built only from lines in sequence, from if/else, and from the while, do, and for loops.

4.2.3.5Drawing tools

No special tool is required to draw a flowchart. The choice depends on what the diagram will be used for:

  • Pen and paper: The fastest way for a first draft; erasing and redrawing is easy. In exams, too, diagrams are drawn by hand.
  • Word and PowerPoint: All the basic symbols are in the Flowchart group of the Insert → Shapes menu. Because connector arrows stick to the boxes, the arrow moves with a box when it is moved.
  • draw.io (diagrams.net): It is free and runs in the browser. It offers ready-made flowchart shapes; the drawing can be exported as PNG, SVG, or PDF.
  • Microsoft Visio: A commercial tool used for corporate process and workflow diagrams.
  • Flowgorithm: It does not merely draw the diagram but runs it. It shows the values of variables step by step and translates the diagram into code in many languages, including Java.
  • Mermaid: The diagram is defined with text and the tool draws it. It is often used in documents and code repositories.

Whatever the tool, the meaning of the symbols and the readability rules are the same. The course's Flowchart Runner simulator, like Flowgorithm, executes a diagram step by step; most of the examples in these notes can be tried there as well.

4.2.4Sequential flow

The simplest of the three structures is sequence. All the control structures are built on this foundation: any section without a decision or loop is sequential flow in itself.

4.2.4.1The sequence structure

Definition 4.2.9

Sequential flow is flow in which the steps run in the order they are written, each after the previous one has finished, and exactly once. It contains no branching or repetition; it has a single entry and a single exit.

Figure 4.2.7 shows the diagram that reads two numbers and prints their sum. All the arrows in the diagram point downward; no box has more than one arrow leaving it.

Startread aread bsum = a + bprint sumEnd
Figure 4.2.7: Sequential flow: Start, read a, read b, sum = a + b, print sum, End.
Start
  read a
  read b
  sum = a + b
  print sum
End

In the pseudocode, the four lines between Start and End are indented; each line corresponds to one box in the diagram.

4.2.4.2Executing sequential flow step by step

To execute a diagram is to do by hand the work the computer would do. We start at the Start box. At each step only one box runs. After a box runs, the new values of the variables and the output, if any, are noted, and then we move to the box the arrow points to. If these notes are collected in a table, the result is a trace table. Table 4.2.4 is the trace table of the execution with input a = 4, b = 7.

Table 4.2.4: Trace table of the sequential flow for a = 4, b = 7. A dash shows that the variable does not yet have a value.
StepBox executedabsumOutput
1Start———
2read a4——
3read b47—
4sum = a + b4711
5print sum471111
6End471111
Startread aread bsum = a + bprint sumEnd Startread aread bsum = a + bprint sumEnd Startread aread bsum = a + bprint sumEnd
Figure 4.2.8: Three steps of the sequential flow; the box running at that moment is highlighted. (a) Step 2: a = 4 is read. (b) Step 4: sum = 4 + 7 = 11. (c) Step 6: End is reached.

The table shows two properties of sequential flow clearly. First, each of the six boxes runs exactly once; there is no repeated or skipped row in the table. Second, once a variable receives a value, it keeps it unless it is changed: a becomes 4 at step 2 and stays 4 to the end. When reading the table, each row describes the state “right after this box has run.”

The Java counterpart of the diagram follows the same order:

import java.util.Scanner;

public class Sum {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();             // read a
        int b = in.nextInt();             // read b
        int sum = a + b;                  // sum = a + b
        System.out.println(sum);          // print sum
    }
}

The structure of the program can be summed up in a few words. The line public class Sum gives the program's name. The main method is where the program starts; the counterpart of the Start box in the diagram is its opening brace, and the counterpart of End is the closing brace. Scanner is the ready-made class Java provides for reading data from the keyboard; in.nextInt() reads an integer from the keyboard. That is why each “read” parallelogram becomes a call to nextInt(). The assignment rectangle corresponds exactly to the line int sum = a + b;, and the “print” parallelogram to the line System.out.println(sum);. At the ends of the lines there are comments beginning with //. The compiler ignores them; here they remind us of each line's counterpart in the diagram.

When the program is run with input 4 and 7, it prints 11. With input −3 and 10, it prints 7. In a sequential program, even when the inputs change, the lines that run and their order never change; only the values do.

4.2.4.3Why order matters

In sequential flow, the positions of the boxes are not arbitrary. If the sum box were moved above the reading boxes, a and b would not yet have values and the sum could not be computed. This mistake is easy to notice. More insidious bugs arise from swapping two assignments.

Example 4.2.2

The values of two variables are to be exchanged; this operation is called a swap. If a = 4, b = 7, then after the operation a = 7, b = 4 must hold. A student puts two boxes in the diagram: first a = b, then b = a. What is the result? How is the correct diagram built?

Solution. The proposed diagram is executed step by step. When the a = b box runs, a takes the value of b: a = 7, b = 7. a's old value, 4, is now nowhere. When the b = a box runs, b takes a's current value: b = 7. The result is a = 7, b = 7; the swap has failed.

The problem is that the first assignment erases a's old value. The solution is to store that value first in a third variable. Such a briefly used variable is called a temporary variable. The correct order is three boxes: temp = a, a = b, b = temp. Execution: temp = 4; a = 7; b = 4. The result is a = 7, b = 4.

import java.util.Scanner;

public class Swap {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        int temp = a;                     // a's value is saved
        a = b;
        b = temp;
        System.out.println(a + " " + b);
    }
}

When the program is run with input 4 7, it prints 7 4. The example shows the basic rule of sequential flow: each box works with the values the previous one left behind. An assignment reads the current value of the variable on its right side; not its old or future value.

Common mistake

Reading an assignment like an equality in mathematics. a = b does not say “a and b are equal”; it says “copy the current value of b into a.” After the copy, if b changes, a does not; if a is changed, b is not. Two variables carry the same value only at the moment of the assignment.

4.2.5Conditional flow

A sequential algorithm does the same steps on every input. In most real problems, however, the work to be done depends on the situation: if the grade is below 60 the student fails, if the code is wrong the door does not open, if the temperature is below zero a warning is given. Such choices are shown with the decision symbol.

4.2.5.1The two-way decision

Definition 4.2.10

Conditional flow is flow in which one of two paths is followed according to the result of the condition asked in a decision symbol. If the condition is true, the Yes path runs; if false, the No path. These paths are called branches, and the splitting of the path in two is called branching. The branches merge again at a connector.

Figure 4.2.9 shows the diagram that prints “Pass” or “Fail” according to an exam grade. The passing mark is 60; 60 and above passes.

YesNoStartread gradegrade >= 60 ?print "Fail"print "Pass"End
Figure 4.2.9: Conditional flow: if the grade is 60 or above, “Pass” is printed; otherwise “Fail.” The paths merge at the connector below.
Start
  read grade
  grade >= 60 ?
    Yes → print "Pass"
    No → print "Fail"
End

Three points in the diagram are especially important. Two paths leave the decision symbol, but on each run only one of them is followed. The “Pass” and “Fail” boxes never run together in the same run. The paths merge again at the connector below (●); this point is the single exit of the decision structure. Finally, the boundary value of the condition deserves attention. Because the passing mark is “60 and above,” the condition is written grade >= 60. Had grade > 60 been written, a student who scored exactly 60 would fail.

4.2.5.2Executing the decision step by step

To fully understand a conditional diagram, it must be executed at least twice. One of the inputs must run the Yes path and the other the No path. Table 4.2.5 summarizes the diagram on three inputs: grade = 72, grade = 45, and the boundary value grade = 60.

Table 4.2.5: Three runs of the Pass/Fail diagram. In each run one of the boxes never runs.
gradeDecisionArrow followedBox executedBox that never runs
7272 >= 60 → trueYesprint "Pass"No branch
4545 >= 60 → falseNoprint "Fail"Yes branch
6060 >= 60 → trueYesprint "Pass"No branch

In the first run the user enters 72 and grade = 72. The decision box asks 72 >= 60; the answer is true. Flow continues along the Yes arrow and “Pass” is printed. The “Fail” box never runs in this run. The path rejoins the main flow at the connector and End is reached. In the second run grade = 45. 45 >= 60 is false; the No path is followed, “Fail” is printed, and this time the “Pass” box does not run. Together, the two runs have executed every box in the diagram at least once.

YesNoStartread gradegrade >= 60 ?print "Fail"print "Pass"End YesNoStartread gradegrade >= 60 ?print "Fail"print "Pass"End
Figure 4.2.10: Two runs of the same diagram. (a) grade = 72: the “print Pass” box on the Yes branch runs. (b) grade = 45: the “print Fail” box on the No branch runs.

The third row is the boundary value. When 60 is entered, 60 >= 60 is true and “Pass” is printed. This row immediately exposes a diagram in which > was mistakenly written instead of >= in the condition: that diagram would print “Fail” for 60. 72 and 45 cannot catch this error, because the two diagrams give the same result on these inputs.

The Java counterpart of the diagram is the if/else statement:

import java.util.Scanner;

public class PassFail {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int grade = in.nextInt();          // read grade
        if (grade >= 60) {                 // grade >= 60 ?
            System.out.println("Pass");   // Yes branch
        } else {
            System.out.println("Fail");   // No branch
        }
    }
}

After the word if, the condition is written in parentheses. If the condition is true, the inside of the first pair of braces runs; if false, the inside of the braces after the word else runs. The decision symbol corresponds to the condition in parentheses, the Yes branch to the first block, and the No branch to the else block. The last closing brace also stands in for the connector: after the two blocks end, execution continues from the same point. The program prints “Pass” for 72, 60, and 100, and “Fail” for 45, 59, and 0.

4.2.5.3The one-way decision

In some decisions, only one of the branches has work to do. The absolute-value diagram in Figure 4.2.5 is an example: if the number is negative its sign is changed; if it is not negative, nothing is done. Two arrows still leave the decision here, but the No arrow goes straight to the merge point without passing through any box. In Java this structure is written with an if that has no else part:

import java.util.Scanner;

public class AbsoluteValue {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        if (x < 0) {                      // no box on the No branch: no else needed
            x = -x;
        }
        System.out.println(x);
    }
}

The program prints 5 for −5, 8 for 8, and 0 for 0. The three inputs are chosen deliberately: −5 tries the Yes branch, 8 the No branch, and 0 the boundary. Since 0 < 0 is false, 0 stays as it is; its absolute value is 0 anyway.

Another common example of a decision structure is the odd/even test. Whether a number is even is found by looking at the remainder of its division by 2. The remainder operation is written % in Java: 7 % 2 is 1 and 12 % 2 is 0. The decision box gets x % 2 == 0 ?; the Yes branch prints “even” and the No branch prints “odd.”

import java.util.Scanner;

public class EvenOdd {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        if (x % 2 == 0) {                 // x % 2 == 0 ?
            System.out.println("even");
        } else {
            System.out.println("odd");
        }
    }
}
Common mistake

Testing for an odd number with the condition x % 2 == 1 ?. This condition works for positive numbers, but in Java the sign of the remainder follows the sign of the dividend: -3 % 2 is −1, not 1. So for −3, x % 2 == 1 comes out false and an odd number is printed as “even.” The question x % 2 == 0 ?, on the other hand, gives the right answer for −3 too: -3 % 2 == 0 is false, and “odd” is printed. When the remainder is compared with zero, the sign problem disappears.

4.2.5.4The largest of three numbers

Finding the larger of two numbers needs a single decision. With three numbers the decisions multiply, and how the diagram is built starts to matter. A widely used method is the “candidate” idea. The first number is taken as the largest for now. Then the other numbers are compared with this candidate one by one; if a larger one turns up, the candidate changes.

YesNoYesNoStartread a, b, cmax = ab > max ?max = bc > max ?max = cprint maxEnd
Figure 4.2.11: The largest of three numbers. We start with max = a; if b is larger, max = b; then if c is larger, max = c.
Start
  read a, b, c
  max = a
  b > max ?  Yes → max = b
  c > max ?  Yes → max = c
  print max
End

Figure 4.2.11 is the diagram of the method. Two decisions come one after the other, and each has a box only on its Yes branch; the No branches pass straight to the next step. That is, the diagram consists of two one-way decisions placed one after the other inside a sequence. It is a nice example of structures growing by being attached to one another.

Example 4.2.3

The diagram will be executed first for (a, b, c) = (4, 9, 7), then for (3, 2, 8). Which path is followed at each decision, and how does max change?

Solution. In the first run the three numbers are read and max = 4. At the first decision 9 > 4 is true; max = 9. At the second decision 7 > 9 is false; max does not change and 9 is printed.

Trace for (4, 9, 7)
Box executedDecisionmax
max = a—4
b > max ?9 > 4 → Yes4
max = b—9
c > max ?7 > 9 → No9
print maxoutput: 99

In the second run we start with max = 3. 2 > 3 is false; the Yes box of the first decision does not run. 8 > 3 is true; max = 8 and 8 is printed.

Trace for (3, 2, 8)
Box executedDecisionmax
max = a—3
b > max ?2 > 3 → No3
c > max ?8 > 3 → Yes3
max = c—8
print maxoutput: 88

Together, the two runs have tried both branches of both decisions. Each decision is asked only once. Even if the quantity of numbers grows, the method does not change: for ten numbers, nine decisions are lined up one after another.

import java.util.Scanner;

public class Largest {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
        int max = a;                      // first candidate
        if (b > max) {
            max = b;
        }
        if (c > max) {
            max = c;
        }
        System.out.println(max);
    }
}

The program prints 9 for (4, 9, 7) and 8 for (3, 2, 8). On the input (9, 4, 7), where the largest number comes first, both decisions are No and 9 is printed. If the three numbers are equal, for example (5, 5, 5), the decisions are again No; max stays 5.

Common mistake

Starting the candidate with a fixed value, for example max = 0, instead of the first number. As long as the inputs are positive this also gives the right result; the error appears only when all the inputs are negative. For (−2, −7, −1), −2 > 0, −7 > 0, and −1 > 0 are all false; the candidate never changes and 0 is printed. Yet 0 is not even one of the inputs. The correct diagram starts with max = a and prints −1 on this input.

4.2.5.5The multi-way decision: a decision chain

A decision box has only two exits. When there are more than two options, the decisions are lined up like a chain: each decision is placed on the No branch of the previous one. This is called a multi-way decision.

YesNoYesNoYesNoread tt < 0 ?print "Freezing"t < 15 ?print "Cold"t < 25 ?print "Mild"print "Hot"End
Figure 4.2.12: The decision chain: for temperature t, “Freezing” is printed if t < 0, “Cold” if t < 15, “Mild” if t < 25, and “Hot” otherwise.

Figure 4.2.12 sorts a temperature value into one of four classes. The rule by which the chain works is this: the decisions are asked in order from top to bottom; the branch of the first true condition runs, and the decisions after it are never asked. If no condition is true, the bottom No branch runs.

Table 4.2.6: Executing the decision chain on five inputs. The number of decisions asked depends on the position of the first true condition.
sDecisions askedNumber of decisionsOutput
−5t < 0 ? Yes1Freezing
10t < 0 ? No · t < 15 ? Yes2Cold
15t < 0 ? No · t < 15 ? No · t < 25 ? Yes3Mild
18t < 0 ? No · t < 15 ? No · t < 25 ? Yes3Mild
30t < 0 ? No · t < 15 ? No · t < 25 ? No3Hot

The t = 18 row of Table 4.2.6 reads step by step as follows. The first decision is the question 18 < 0; it is false and the No branch goes to the second decision. 18 < 15 is also false. The third decision, 18 < 25, is true; “Mild” is printed. For t = −5, on the other hand, the first decision is true and the other two decisions are never asked.

Each decision in the chain checks only the upper bound. When the question t < 15 is asked, it is certain that t is 0 or greater; otherwise execution would never have reached this decision. So there is no need for a two-sided condition such as “0 ≤ t and t < 15.” This rule also shows which class the boundary values fall into: for t = 15, 15 < 15 is false, the decision moves on along the chain, and 15 is “Mild.” t = 0 is “Cold.”

The order of the decisions matters. If the decisions were lined up in reverse order, that is, if t < 25 ? were asked first, then for t = −5 −5 < 25 comes out true and “Mild” is printed; the “Freezing” branch is never reached. The same happens for t = 10. The general rule is short: ask the narrow condition first, the wide condition later. If the number of options is n, n − 1 decisions are needed; for four classes there are three decisions.

In Java, a decision chain is written in the form if … else if … else. Each else if is the No branch of the previous condition; the last else is the case where no condition held:

import java.util.Scanner;

public class Temperature {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        if (t < 0) {
            System.out.println("Freezing");
        } else if (t < 15) {
            System.out.println("Cold");
        } else if (t < 25) {
            System.out.println("Mild");
        } else {
            System.out.println("Hot");
        }
    }
}

The program prints “Freezing” for −5, “Cold” for 0 and 10, “Mild” for 15 and 18, and “Hot” for 25 and 30. These seven inputs try the four exits of the chain and every boundary value.

4.2.5.6Compound conditions: AND and OR

Some decisions require two conditions to be evaluated together. A car-rental company requires the customer both to be at least 18 years old and to hold a driver's license. A calendar app prints “Weekend” if the day is Saturday or Sunday. Expressions like these, which combine two conditions, are called compound conditions.

Definition 4.2.11

A compound condition joined with AND is true if both conditions are true; if even one is false, it is false. A compound condition joined with OR is true if at least one of the conditions is true; if both are false, it is false. In Java, AND is written with the operator && and OR with ||.

A compound condition can be written in a single decision box: age >= 18 AND has license ?. If detail is needed in the diagram, it is expanded into two separate decisions. Figure 4.2.13 shows how the two connectives are drawn with two decisions.

AND: both must be Yesage >= 18 ?has license ?YesCan rentYesCannot rentNoNoOR: one Yes is enoughday == Sat ?day == Sun ?NoWeekdayNoWeekendYesYes
Figure 4.2.13: Drawing a compound condition with two decisions. On the left, AND: both decisions must be Yes. On the right, OR: it is enough if one of the decisions is Yes.

In the AND structure, the second decision is placed on the Yes branch of the first. If the first decision is No, the result is already No and the second decision is never asked. In the OR structure, the second decision is on the No branch of the first. If the first decision is Yes, the result is already Yes and there is no need for the second. Table 4.2.7 and Table 4.2.8 show this behavior for all cases.

Table 4.2.7: The AND decision. When the first decision is No, the second is not asked.
agelicenseage >= 18 ?has license ?Result
20yesYesYesCan rent
20noYesNoCannot rent
16yesNonot askedCannot rent
16noNonot askedCannot rent
Table 4.2.8: The OR decision. When the first decision is Yes, the second is not asked.
dayday == Sat ?day == Sun ?Result
SatYesnot askedWeekend
SunNoYesWeekend
TueNoNoWeekday
Definition 4.2.12

Short-circuit evaluation means that the second condition is not evaluated at all when the first condition already settles the result of the compound condition. In A && B, if A is false, B is not looked at; in A || B, if A is true, B is not looked at.

The operators && and || in Java work in the same way as the two-decision diagrams in Figure 4.2.13. This behavior not only saves time but also prevents some errors. In the condition count > 0 && total / count > 50, if count is 0 the second part is never evaluated; so no division-by-zero error occurs.

import java.util.Scanner;

public class Rental {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int age = in.nextInt();
        boolean hasLicense = in.nextBoolean();   // true: has a license
        String day = in.next();                  // Mon, Tue, ..., Sat, Sun
        if (age >= 18 && hasLicense) {
            System.out.println("Can rent");
        } else {
            System.out.println("Cannot rent");
        }
        if (day.equals("Sat") || day.equals("Sun")) {
            System.out.println("Weekend");
        } else {
            System.out.println("Weekday");
        }
    }
}

With the input “20 true Sat” the program prints “Can rent” and “Weekend”; with the input “16 true Sun” it prints “Cannot rent” and “Weekend.” To test a compound condition, both exits of each decision are tried. In the AND example, the inputs (20, yes), (20, no), and (16, —) run three different paths. Whether a 16-year-old has a license does not change the result, because the second decision is not asked.

4.2.5.7Leap year

The classic example showing the importance of order in a decision chain is the leap-year rule. In the Gregorian calendar the rule has three parts: years divisible by 4 are leap years; but those divisible by 100 are not; and those divisible by 400 are leap years again. In a leap year February has 29 days.

The rule has exceptions, and the exceptions have exceptions. When such a rule is turned into a diagram, the narrowest condition goes first. Divisibility by 400 is a special case of divisibility by 100, and divisibility by 100 is a special case of divisibility by 4. That is why the decisions are asked in the order 400, 100, 4.

YesNoYesNoYesNoStartread yearyear % 400 == 0 ?print "Leap"year % 100 == 0 ?print "Common"year % 4 == 0 ?print "Leap"print "Common"End
Figure 4.2.14: The leap-year diagram: a chain of three decisions made up of year % 400, year % 100, and year % 4; four exits.
Start
  read year
  year % 400 == 0 ?  Yes → print "Leap"
  year % 100 == 0 ?  Yes → print "Common"
  year % 4 == 0 ?    Yes → print "Leap"
  No → print "Common"
End
Table 4.2.9: Executing the leap-year diagram on four inputs. Each cell shows the remainder and the result of the decision.
yearyear % 400year % 100year % 4Decision askedOutput
202424 → No24 → No0 → Yes3Leap
1900300 → No0 → Yesnot asked2Common
20000 → Yesnot askednot asked1Leap
202323 → No23 → No3 → No3Common

Table 4.2.9 shows the path each of the four inputs takes. For 2024, 2024 % 400 = 24 and 2024 % 100 = 24 are not zero; both decisions are No. Since 2024 % 4 = 0, the third decision is Yes and “Leap” is printed. For 1900, 1900 % 400 = 300 is not zero but 1900 % 100 = 0. The second decision is Yes, “Common” is printed, and the third decision is never asked. 1900 is not a leap year even though it is divisible by 4; a diagram that looked only at the question year % 4 == 0 would be wrong here. For 2000 the first decision is Yes: although 2000 is divisible by 100, it is also divisible by 400, so it is a leap year. 2023 runs the last branch, where all three decisions are No.

YesNoYesNoYesNoStartread yearyear % 400 == 0 ?print "Leap"year % 100 == 0 ?print "Common"year % 4 == 0 ?print "Leap"print "Common"End YesNoYesNoYesNoStartread yearyear % 400 == 0 ?print "Leap"year % 100 == 0 ?print "Common"year % 4 == 0 ?print "Leap"print "Common"End
Figure 4.2.15: Two early exits in the leap-year chain. (a) 1900: the second decision (year % 100 == 0) is Yes; the third decision is not asked. (b) 2000: the first decision is Yes; the remaining two decisions are not asked.

The four inputs run each of the diagram's four exits once. This is exactly the goal when testing a decision chain. The Java counterpart is again an if … else if … else chain:

import java.util.Scanner;

public class LeapYear {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int year = in.nextInt();
        if (year % 400 == 0) {
            System.out.println("Leap");
        } else if (year % 100 == 0) {
            System.out.println("Common");
        } else if (year % 4 == 0) {
            System.out.println("Leap");
        } else {
            System.out.println("Common");
        }
    }
}

The program prints “Leap” for 2024 and 2000, and “Common” for 1900 and 2023. The first exception in the near future is the year 2100: 2100 is divisible by 100 but not by 400; the program prints “Common” for this year. 1600 is a leap year because it is divisible by 400.

Common mistake

Starting the chain with the wide condition. If year % 4 == 0 ? is asked first and “Leap” is printed directly on its Yes branch, 1900 and 2100 are also counted as leap years. Because the 100 and 400 rules concern only years divisible by 4, their turn never comes. The decisions in the chain must be arranged from the narrow condition to the wide one.

4.2.6Repetitive flow

What makes a computer powerful is that it can do the same job thousands of times without getting tired. Adding up the grades of 30 students in a class means doing the same two steps 30 times: read the grade, add it to the total. Instead of drawing these steps 30 times in the diagram, we draw them once and make them repeat with an arrow that goes back.

4.2.6.1The loop structure

Definition 4.2.13

Repetitive flow, or a loop, is flow in which a group of steps runs again and again as long as a condition is true. The repeated steps are called the loop body, and one run of the body is called an iteration. The arrow that returns from the end of the body to the condition forms the loop.

Figure 4.2.16 shows the diagram that prints the numbers from 1 to 5. The diagram has three parts. The i = 1 box gives the initial value of the counter. The decision box i <= 5 ? decides whether the loop continues. The two boxes on the Yes branch, “print i” and i = i + 1, are the loop body. The arrow leaving the end of the body turns left and enters the decision box again.

YesrepeatNoStarti = 1i <= 5 ?print ii = i + 1End
Figure 4.2.16: Repetitive flow: we start with i = 1; while i <= 5, i is printed and increased by 1. The “repeat” arrow on the left forms the loop.
Start
  i = 1
  i <= 5 ?
    Yes → print i
            i = i + 1
            back to the decision
    No → End

In this diagram the condition is asked before the body. If the condition is false on the very first try, the body never runs. Such loops are called pre-test loops. When the condition is false, the No branch leaves the loop and goes to End.

For the loop to end some day, there must be an operation on the repeat path that changes the condition. Here this operation is i = i + 1. i grows on every iteration and eventually exceeds 5. If this box were forgotten, i would stay 1, 1 <= 5 would come out true every time, and the diagram would print 1 forever. A loop that never ends is called an infinite loop.

4.2.6.2Executing a loop step by step

Because the same boxes run again and again in a loop, each iteration is shown with one row in the trace table. Table 4.2.10 gives all the iterations of the diagram.

Table 4.2.10: Trace table of the loop that prints the numbers 1 to 5. The last row is the final decision, where the loop is exited.
Iterationi (before the decision)DecisionPrintedi (at the end of the iteration)
111 <= 5 → true12
222 <= 5 → true23
333 <= 5 → true34
444 <= 5 → true45
555 <= 5 → true56
—66 <= 5 → false——

The execution goes as follows. The counter gets its initial value: i = 1. At the decision box 1 <= 5 is asked; it is true and we enter the Yes branch, that is, the loop body. 1 is printed. The i = i + 1 box makes i 2. The returning arrow takes execution back to the decision box. 2 <= 5 is also true; 2 is printed and i = 3. The same cycle repeats for 3, 4, and 5. After 5 is printed, i = 6. At the decision box 6 <= 5 is asked; this time the answer is false and the No branch leads to End.

YesrepeatNoStarti = 1i <= 5 ?print ii = i + 1End YesrepeatNoStarti = 1i <= 5 ?print ii = i + 1End
Figure 4.2.17: Two moments of the loop. (a) End of iteration 1: i = 1 + 1 = 2; the returning arrow leads to the decision. (b) The final decision: 6 <= 5 is false; the No branch leaves the loop.

Two counts come out of the table. The body ran 5 times but the condition was asked 6 times. This holds for every pre-test loop: the decision runs one more time than the body, because the last attempt is the false answer that ends the loop. When the loop is exited, the value of i is 6, not 5. The value of the counter after the loop is a question that is often asked and often answered wrongly.

In Java, a pre-test loop is written with while. As long as the condition in parentheses is true, the inside of the braces runs again; the closing brace stands in for the returning arrow:

public class OneToFive {
    public static void main(String[] args) {
        int i = 1;                        // initial value of the counter
        while (i <= 5) {                  // decision: i <= 5 ?
            System.out.print(i + " ");    // print i
            i = i + 1;                    // update the counter
        }                                 // returning arrow: back to the decision
        System.out.println();
    }
}

The program prints 1 2 3 4 5. Unlike println, System.out.print adds no line break; the numbers are therefore printed on the same line with a space between them. The System.out.println() line after the loop only ends the line.

4.2.6.3Counter and accumulator

Most loops contain two kinds of variable. One counts which iteration the loop is on; the other holds the result that builds up from iteration to iteration.

Definition 4.2.14

A counter is a variable that tracks how many repetitions have been made; it increases by 1 on every iteration. An accumulator is a variable that holds the partial result; on every iteration a new value is added to it (or multiplied into it). The starting value of the accumulator is chosen according to the operation: 0 for a sum, 1 for a product.

The choice of starting value is not arbitrary. For addition we choose 0, because adding 0 to a number does not change it; after the first iteration, the sum is the first number itself. For a product, 1 plays the same role. If a product accumulator is mistakenly started at 0, it is multiplied by 0 on every iteration and the result is always 0. For example, the product of the numbers from 1 to 5 is 1 × 1 × 2 × 3 × 4 × 5 = 120; if the accumulator starts at 0, we get 0 × 1 × 2 × 3 × 4 × 5 = 0.

YesNoStartcount = 0, sum = 0count < 3 ?read xsum = sum + xcount = count + 1print sumEnd
Figure 4.2.18: Counter and accumulator: three numbers are read and summed. While count < 3, x is read, sum = sum + x and count = count + 1 are done.
Start
  count = 0, sum = 0
  count < 3 ?
    Yes → read x
            sum = sum + x
            count = count + 1
            back to the decision
    No → print sum
End

Figure 4.2.18 is the diagram that reads three numbers and prints their sum. count is the counter and sum is the accumulator. Both receive the value 0 once, before the loop. Table 4.2.11 gives their values at the end of each iteration when the inputs are 4, 7, and 2.

Table 4.2.11: Iteration-by-iteration values of the counter and accumulator for inputs 4, 7, 2.
StatexcountsumNext decision
start—000 < 3 → true
Iteration 14141 < 3 → true
Iteration 272112 < 3 → true
Iteration 323133 < 3 → false

In the first iteration x = 4 is read. The accumulator becomes sum = 0 + 4 = 4, the counter becomes count = 0 + 1 = 1, and the arrow returns to the decision. In the second iteration x = 7 is read; sum = 4 + 7 = 11, count = 2. In the third iteration x = 2 is read; sum = 11 + 2 = 13, count = 3. At the decision box 3 < 3 is asked; it is false and the loop is exited. The sum is printed: 13. The counter held how many times the loop ran, and the accumulator held the result.

count3+1 per iterationsum13+x per iteration
Figure 4.2.19: When the loop ends, the counter is 3 and the accumulator is 13. The counter grew by 1 on each iteration and the accumulator by x.
import java.util.Scanner;

public class SumOfThree {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = 0, sum = 0;
        while (count < 3) {
            int x = in.nextInt();         // read x
            sum = sum + x;                // accumulator
            count = count + 1;            // counter
        }
        System.out.println(sum);
    }
}

The program prints 13 for the input 4 7 2 and 12 for 10 −3 5. In the Java code the variable x is declared inside the loop. On every iteration a new value is read and the value of x from the previous iteration is no longer needed.

Common mistake

Resetting the accumulator inside the loop. If the sum = 0 box is mistakenly drawn at the start of the loop body, every iteration begins by erasing the sum of the previous iterations. For inputs 4, 7, 2 the table becomes:

Trace of the faulty diagram: sum is reset on every iteration.
Iterationxsum (after reset)sum (after adding)count
Iteration 14041
Iteration 27072
Iteration 32023

2 is printed instead of 13; that is, only the last value survives. Boxes that give starting values must run once, before the loop.

4.2.6.4Sum from 1 to n

A classic example in which a counter and an accumulator are used together is the sum of the numbers from 1 to n. This time the counter does not merely count iterations; it is itself the number to be added.

YesNoStartread nsum = 0, i = 1i <= n ?sum = sum + ii = i + 1print sumEnd
Figure 4.2.20: Sum from 1 to n. n is read; we start with sum = 0, i = 1; while i <= n, sum = sum + i and i = i + 1 are done.
Start
  read n
  sum = 0, i = 1
  i <= n ?
    Yes → sum = sum + i
            i = i + 1
            back to the decision
    No → print sum
End

In the diagram i is the counter and sum is the accumulator. Table 4.2.12 shows the execution for n = 4. The expected result is 1 + 2 + 3 + 4 = 10.

Table 4.2.12: Trace table of the sum-from-1-to-n diagram for n = 4.
IterationiDecisionsumi (updated)
Iteration 111 <= 4 → true0 + 1 = 12
Iteration 222 <= 4 → true1 + 2 = 33
Iteration 333 <= 4 → true3 + 3 = 64
Iteration 444 <= 4 → true6 + 4 = 105
exit55 <= 4 → false10—

Each row of the table is one iteration. In the first iteration 1 <= 4 is true; sum becomes 0 + 1 = 1 and i rises to 2. In the second iteration sum becomes 1 + 2 = 3, in the third 3 + 3 = 6, in the fourth 6 + 4 = 10. When i = 5, 5 <= 4 is false and the loop is exited. The body ran n = 4 times and the decision n + 1 = 5 times. 10 is printed on the screen.

The result can also be checked with a formula. Writing the numbers from 1 to n once in increasing and once in decreasing order, one under the other, and adding column by column gives the formula step by step. For n = 4:

Writing the sum from 1 to 4 twice
increasing1234
decreasing4321
column sum5555

The sum of each column is n + 1 = 5, and there are n = 4 columns. The sum of the two rows is 4 × 5 = 20. This is twice the sum we are looking for; the sum is 20 ÷ 2 = 10. The general formula is n(n + 1) / 2. The formula confirms, by an independent route, that the diagram works correctly.

What happens if n = 0 is entered? With i = 1, the question 1 <= 0 is false at the first try. The body never runs and 0 is printed. This is also the right answer: no numbers have been added. The formula gives 0 × 1 / 2 = 0 as well. The pre-test loop's property that “the body may never run” is useful here.

4.2.6.5Counter-controlled and sentinel loops

In the loops so far, the number of iterations was known in advance: 5 times, 3 times, n times. In some jobs this number is not known. The cashier does not know in advance how many items will be scanned; when the items run out, they press the “done” key. A teacher entering grades, instead of counting the grades, types a special value at the end. Such a special value is called a sentinel value.

Definition 4.2.15

A counter-controlled loop is a loop whose number of repetitions is known in advance and controlled with a counter. A sentinel value is a special value that signals the end of the data and is chosen so that it cannot occur in the real data. A sentinel-controlled loop is a loop that runs until the sentinel value is read.

Table 4.2.13: Comparison of counter-controlled and sentinel-controlled loops.
Controlled by a counterControlled by a sentinel
Number of repetitionsKnown in advance (n times)Unknown; stops when a special value arrives
Decisioni <= n ?x == −1 ? (has the sentinel arrived?)
ExampleRead the grades of the 30 students in a classItems scanned at a checkout; until the “done” key
In Java, usuallyforwhile

The choice of sentinel depends on the data. If grades are between 0 and 100, −1 is a suitable sentinel, because no student scores −1. 0 is not suitable: a student's grade really can be 0, and that grade would be mistakenly interpreted as “data finished.”

NoYesStartsum = 0, count = 0read xx == −1 ?sum = sum + xcount = count + 1avg = sum / countprint avgEnd
Figure 4.2.21: Sentinel-controlled loop: read until x == −1, add, count; then print the average. The returning arrow goes back to the read box.
Start
  sum = 0, count = 0
  read x
  x == -1 ?  Yes → go to line 7
  sum = sum + x
  count = count + 1;  back to line 3
  avg = sum / count
  print avg
End

Figure 4.2.21 shows two important details of the sentinel-controlled loop. First, the decision box comes right after the read box, before adding and counting. This way, when the sentinel is read, we leave the loop without it being added or counted. Second, the returning arrow goes back not to the decision box but to the front of the read box. A new number must be read on every iteration; if the arrow went back to the decision, the same x would be processed over and over.

Table 4.2.14: Trace table of the sentinel-controlled loop for inputs 80, 64, 90, −1.
x readx == −1 ?sumcount
80No801
64No1442
90No2343
−1Yes (sentinel)2343

Table 4.2.14 gives the execution for inputs 80, 64, 90, −1. Each grade read is first compared with the sentinel. 80, 64, and 90 are real grades; they are added to the sum and counted. When −1 is read, the decision is Yes and the loop ends. The average is 234 / 3 = 78. The body ran 3 times and the decision 4 times. How many grades would be entered was not known in advance; the data itself stopped the loop.

If the first input is the sentinel, the body never runs and the counter stays 0. In that case the average computation becomes a division by zero. That is why count > 0 ? is asked before the division. The Java counterpart includes this check as well:

import java.util.Scanner;

public class GradeAverage {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int sum = 0, count = 0;
        int x = in.nextInt();             // the first grade is read before the loop
        while (x != -1) {                 // has the sentinel arrived?
            sum = sum + x;
            count = count + 1;
            x = in.nextInt();             // next grade: the returning arrow goes to the read box
        }
        if (count > 0) {
            double avg = (double) sum / count;
            System.out.println(avg);
        } else {
            System.out.println("No grades entered");
        }
    }
}

In the Java code the first grade is read once before the loop, and the later grades are read at the end of the body. This is how the diagram's detail “the returning arrow goes to the read box” is written with while. Because the average can have a fractional part, it is computed as a double; the expression (double) sum converts the sum to a floating-point number before the division. The program prints 78.0 for 80 64 90 −1, 62.5 for 55 70 −1, and “No grades entered” for −1 alone.

Common mistake

Testing the sentinel after processing. If the decision box is drawn below the add and count boxes, −1 is also processed as data:

Faulty order: first add and count, then ask about the sentinel.
x readsumcountx == −1 ?
80801No
641442No
902343No
−12334Yes

The sum becomes 233 instead of 234, the counter 4 instead of 3, and the average comes out as 233 / 4 = 58.25 instead of 78. The decision about the sentinel must come before every operation that uses the value.

4.2.6.6Nested loops

The single-entry, single-exit rule of structured programming allows one structure to be placed inside another. A decision can contain another decision on one of its branches. A loop body can contain a second loop.

Definition 4.2.16

A nested loop is a loop that has another loop in its body. The outer one is called the outer loop and the inner one the inner loop. On every iteration of the outer loop, the inner loop runs from start to finish.

The multiplication table is the most familiar example of a nested loop. The outer loop moves through the rows (i), the inner loop through the columns (j); i × j is written in each cell. Figure 4.2.22 shows the 3 × 3 table. The outer loop runs 3 iterations, and the inner loop runs 3 iterations on each outer iteration. The inner body runs a total of 3 × 3 = 9 times.

inner loop: j = 1, 2, 3 →outer loop: i = 1, 2, 3 ↓j=1j=2j=3i=1123i=2246i=3369
Figure 4.2.22: The nested-loop grid. The outer loop moves through the rows (i = 1, 2, 3), the inner loop through the columns (j = 1, 2, 3); the cells hold i × j. The highlighted row is the three iterations of j while i = 2.

To keep the diagram small, a 2 × 2 table is drawn. Figure 4.2.23 shows how the two loops fit together.

NoNoStarti = 1i <= 2 ?j = 1j <= 2 ?print i × jj = j + 1i = i + 1EndYesYes
Figure 4.2.23: Nested loops: i from 1 to 2, j from 1 to 2; the inner body prints i × j. When the inner loop ends, i increases and we return to the outer decision.
Start
  i = 1
  i <= 2 ?  (No → End)
    j = 1
    j <= 2 ?  (No → i = i + 1)
      print i × j
      j = j + 1, back to inner decision
    end line (println), i = i + 1, back to outer decision
End

The body of the outer loop consists of three parts: j = 1, the whole inner loop, and i = i + 1. It matters that the j = 1 box is inside the outer body. On every outer iteration j becomes 1 again; this way the inner loop starts each row from the beginning.

Table 4.2.15: Trace table of the 2 × 2 nested loop. Each row is one inner-decision question.
ijInner decisionAction
111 <= 2 → true1 × 1 = 1
122 <= 2 → true1 × 2 = 2
133 <= 2 → falseend of line
211 <= 2 → true2 × 1 = 2
222 <= 2 → true2 × 2 = 4
233 <= 2 → falseend of line

Table 4.2.15 gives the execution. With i = 1 the outer decision 1 <= 2 is true. j = 1; the inner decision is true and 1 × 1 = 1 is printed. j = 2; 1 × 2 = 2 is printed. When j = 3 the inner decision is false and the inner loop ends. The end of line is printed, i = 2, and we return to the outer decision. In the second outer iteration j starts again at 1 and the same path is followed: 2 and 4 are printed. When i = 3 the outer decision 3 <= 2 is false and we go to End. The output is a small multiplication table:

1 2
2 4

The inner body ran 2 × 2 = 4 times. In general, if the outer loop runs n iterations and the inner loop m, the inner body runs n × m times. As the numbers grow, this product grows quickly: in a 1000 × 1000 table the inner body runs a million times.

public class MultiplicationTable {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 2) {                  // outer decision
            int j = 1;                    // inner counter is 1 again on every outer iteration
            while (j <= 2) {              // inner decision
                System.out.print(i * j + " ");
                j = j + 1;
            }
            System.out.println();         // end of line
            i = i + 1;
        }
    }
}

The program prints two lines: 1 2 and 2 4. In the Java code the line int j = 1; is inside the outer loop's braces. If this line is moved before the outer loop, j stays at 3 in the second outer iteration, the inner decision comes out false at the first try, and the second line is printed empty.

A large number of nested structures can be a sign that a part of the algorithm should be drawn as a separate subprocess. Three or four levels of nested decisions and loops make both the diagram and the code unreadable.

4.2.6.7The number-guessing game

The computer holds a secret number between 1 and 100. The player guesses; the computer gives a hint, “Higher” or “Lower.” The game ends when the guess is right, and the number of tries is printed. The player's guesses determine how many iterations the loop runs; in this respect the game is a kind of sentinel-controlled loop.

YesNoYesNoStartsecret = 37, tries = 0read guesstries = tries + 1guess == secret ?guess < secret ?print "Higher"print "Lower"print "Got it"End
Figure 4.2.24: The number-guessing game: the guess is read again, with a hint, until it equals the secret number. On a correct guess “Got it” is printed and the game ends.
Start
  secret = 37, tries = 0
  read guess
  tries = tries + 1
  guess == secret ?
    Yes → print "Got it (try " tries ")", End
  guess < secret ?
    Yes → print "Higher"
    No → print "Lower"
  back to line 3 (read)
End

There are two decisions in the diagram. The first is the question guess == secret ? and it ends the loop. The second is the question guess < secret ? and it decides which hint is given. The second decision is on the No branch of the first; if the guess is right, the hint question is never asked. After the two hint boxes, the arrow returns to the read box. The secret number is normally chosen at random; here 37 is used so that the trace can be repeated.

Table 4.2.16: Trace table for secret number 37 and guesses 50, 25, 37.
guesstriesguess == 37 ?guess < 37 ?Output
501NoNoLower
252NoYesHigher
373Yesnot askedGot it (try 3)

The player first enters 50; tries = 1. 50 == 37 is false, so we move to the hint question. 50 < 37 is also false; since the guess is too high, “Lower” is printed. The second guess is 25; 25 < 37 is true and “Higher” is printed. The third guess is 37; the equality is true and “Got it (try 3)” is printed.

import java.util.Scanner;

public class NumberGuess {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int secret = 37;                  // in the game: new java.util.Random().nextInt(100) + 1
        int tries = 0;
        int guess = in.nextInt();
        tries = tries + 1;
        while (guess != secret) {         // guess == secret ? the No branch stays in the loop
            if (guess < secret) {
                System.out.println("Higher");
            } else {
                System.out.println("Lower");
            }
            guess = in.nextInt();
            tries = tries + 1;
        }
        System.out.println("Got it (try " + tries + ")");
    }
}

The Java program writes the diagram with a slightly different layout. The first guess is read before the loop, and the loop condition becomes guess != secret. The next guess is read at the end of the body. This is the same layout as in the sentinel-controlled loop. With the input 50 25 37 the program prints “Lower,” “Higher,” and “Got it (try 3)”; with 20 40 37 it prints “Higher,” “Lower,” and “Got it (try 3).” If 37 is entered on the first guess, the loop body never runs and “Got it (try 1)” is printed.

The game has a good strategy: guess the middle of the remaining range each time. In the range 1–100 the first guess is 50; if the hint is “Lower,” the range drops to 1–49, and if “Higher,” to 51–100. Each guess splits the range roughly in half. In the worst case the range shrinks as 100, 50, 25, 12, 6, 3, 1; so 7 guesses are always enough. The reason is that 27 = 128 is greater than 100.

4.2.6.8The post-test loop

In some jobs the loop body must run at least once. The user is asked for a number between 1 and 5; if the number entered is invalid, the question is asked again. Whether the number is valid cannot be asked before it is read. In this case it is more natural to put the condition at the end of the body.

Definition 4.2.17

A post-test loop is a loop in which the condition is asked after the body. The body runs first and then the condition is examined; so the body runs at least once. In Java it is written in the form do { … } while (condition);.

YesNoStartread num1 <= num <= 5 ?print numEndprint "Invalid"
Figure 4.2.25: Input validation with a post-test loop: num is read; if it is not 1 ≤ num ≤ 5, “Invalid” is printed and it is read again.
Start
  read num
  1 <= num <= 5 ?
    No → print "Invalid", back to read
    Yes → print num
End

In the diagram of Figure 4.2.25, after Start execution goes directly into the read box; there is no decision in between. The decision comes after the reading. On an invalid number the No branch prints “Invalid” and the arrow returns to the read box. This kind of use is called input validation.

Table 4.2.17: Trace table of the post-test loop for inputs 7, 0, 3.
IterationNumber read1 ≤ num ≤ 5 ?Output
17false → NoInvalid
20false → NoInvalid
33true → YesValid: 3

In the first iteration 7 is read before the condition has been asked even once. Then comes the decision: is 1 ≤ 7 ≤ 5? Since 7 is greater than 5, the answer is false; “Invalid” is printed. In the second iteration 0 is read; since 0 is less than 1, it is invalid again. In the third iteration 3 is read; 1 ≤ 3 ≤ 5 is true and “Valid: 3” is printed. The body ran 3 times and the condition was also asked 3 times. Unlike a pre-test loop, here the number of decisions equals the number of body runs.

The condition 1 <= num <= 5 in the diagram is mathematical notation. Java does not accept this form; the two comparisons are joined with a compound condition. The invalidity condition becomes “num is less than 1 OR greater than 5”:

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num;
        do {
            num = in.nextInt();                   // body: read first
            if (num < 1 || num > 5) {
                System.out.println("Invalid");
            }
        } while (num < 1 || num > 5);           // the condition is asked at the end
        System.out.println("Valid: " + num);
    }
}

With the input 7 0 3 the program prints “Invalid” twice and then “Valid: 3.” If the first input is 4, the body runs once and “Valid: 4” is printed directly. In the code the invalidity condition is written twice: once inside the if for the warning, once in the loop condition. The single decision box in the diagram becomes two separate questions in the code.

Common mistake

Thinking the difference between while and do-while is only a difference of notation. The difference shows up when the condition is false at the first try. If the sum-from-1-to-n diagram were drawn as a post-test loop, then for n = 0 the body would run once and the sum would be 1; yet the right answer is 0. Whenever the body may need to never run, a pre-test loop is chosen.

4.2.6.9The flowchart of a for loop

Counter-controlled loops always contain the same four parts: the counter's starting value, the condition, the body, and the update of the counter. Java offers a shorter notation for this pattern: the for loop.

YesNoi = 1i <= n ?sum = sum + ii = i + 1print sum1234
Figure 4.2.26: The four parts of a for loop: (1) initialization i = 1, (2) condition i <= n, (3) body sum = sum + i, (4) update i = i + 1.
for (i = 1; i <= n; i++) {
    sum = sum + i;
}
  1. Initialization (i = 1): runs only once, when entering the loop.
  2. Condition (i <= n): asked before every iteration; a for loop is a pre-test loop.
  3. Body: runs if the condition is true.
  4. Update (i++): runs after the body; then the arrow returns to the condition. i++ is a short way of writing i = i + 1.

Figure 4.2.26 is no different from a while diagram. A for loop merely gathers parts 1, 2, and 4 on one line. Some sources show these three parts in the preparation symbol among the additional symbols (a hexagon, “i = 1 → n”).

public class ForSum {
    public static void main(String[] args) {
        int n = 4, sum = 0;
        for (int i = 1; i <= n; i++) {    // initialization; condition; update
            sum = sum + i;                // body
        }
        System.out.println(sum);
    }
}

The program prints 10 for n = 4; it gives the same result as the sum-from-1-to-n program written with while. Which loop to choose is a matter of readability. When the number of repetitions is known in advance, for reads more clearly; when the data stops the loop, while does.

4.2.6.10Early exit, flag, and jump

Suppose we are looking for the first negative number in an array: a = [4, 7, −2, 5, −8]. Once the number sought is found, the remaining iterations are unnecessary. A second arrow going out of the loop from inside the body ends the loop at once.

Definition 4.2.18

An early exit is leaving a loop from inside the body before the loop's condition has become false; in Java it is done with the break statement. A flag is a true/false variable that records whether an event has happened. Continue, on the other hand, does not leave the loop; it skips the rest of that iteration and returns to the update and the condition.

YesNoNoYesi = 1i <= n ?a[i] < 0 ?i = i + 1print a[i]print "None"Endearly exit
Figure 4.2.27: A loop that looks for the first negative number. The loop has two exits: one from the condition (i <= n false: print “None”) and one from the body (a[i] < 0: print a[i], early exit).

In the diagram the elements of the array are written a[i]: a[1] is the first element of the array and a[2] the second. An array is an ordered list of values of the same type; here there are five numbers, so n = 5.

Table 4.2.18: Search for the first negative number for a = [4, 7, −2, 5, −8].
ia[i]i <= n ?a[i] < 0 ?Done
141 <= 5 → YesNoi = 2
272 <= 5 → YesNoi = 3
3−23 <= 5 → YesYesprint −2, leave the loop

At i = 1, 4 and at i = 2, 7 are not negative. At i = 3, −2 is found and printed; the loop ends by early exit. 5 and −8 are never looked at. If there were no negative number in the array, the loop would exit through the condition at i = 6 and “None” would be printed.

A loop with an early exit has two exits, and this does not obey the single-exit rule of structured programming. If a single exit is wanted, a flag is used. We start with found = false, set found = true when the target is found, and the loop condition becomes i <= n AND not found ?. When the loop ends, the flag is checked to print the result. In Java both ways are used:

public class FirstNegative {
    public static void main(String[] args) {
        int[] a = {4, 7, -2, 5, -8};
        // way 1: early exit with break (a loop with two exits)
        int i = 0;
        while (i < a.length) {
            if (a[i] < 0) {
                break;                    // target found: leave the loop
            }
            i = i + 1;
        }
        if (i < a.length) {
            System.out.println(a[i]);
        } else {
            System.out.println("None");
        }
        // way 2: a single-exit loop with a flag
        boolean found = false;
        int k = 0;
        while (k < a.length && !found) {
            if (a[k] < 0) {
                found = true;
            } else {
                k = k + 1;
            }
        }
        System.out.println(found ? a[k] + "" : "None");
    }
}

Both ways print −2. In Java, array elements are numbered from 0: a[0] is 4 and a[2] is −2. That is why in the code the counter starts at 0 and the condition is i < a.length; a.length is the number of elements in the array (5). In the flag version, the expression !found means “not found.” The condition k < a.length && !found is a compound condition and works with short-circuit evaluation.

Continue, on the other hand, does not end the loop; it only skips the rest of that iteration. For example, if the sum of the non-negative numbers in the array is wanted, the adding step is skipped when a negative number is reached:

public class ContinueExample {
    public static void main(String[] args) {
        int[] a = {4, 7, -2, 5, -8};
        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] < 0) {
                continue;                 // skip the negative, go to the next iteration
            }
            sum = sum + a[i];
        }
        System.out.println(sum);
    }
}

The program prints 4 + 7 + 5 = 16. At −2 and −8, continue runs; the adding line is skipped, i++ runs, and we return to the condition. In a diagram, continue is shown with an arrow from the middle of the body to the update box.

4.2.7From flowchart to Java code

The value of a flowchart comes from its being turned, in the end, into a running program. In the earlier sections the Java counterpart of each structure was given separately. This section gathers the translation into a list of rules and applies it line by line to one complete example.

4.2.7.1Code counterparts of the symbols

Table 4.2.19: Java counterparts of flowchart elements.
Flowchart elementJava counterpart
Start / EndThe opening and closing braces of the main method
Input (read)int a = in.nextInt(); or a variable declaration with a fixed value
Process (assignment)An assignment statement: sum = sum + i;
Output (print)System.out.println(…);
Decision, two branches mergingif (condition) { … } else { … }
Decision chainif … else if … else
Decision + arrow returning from the body (condition first)while (condition) { … } or for
Body + arrow returning to the decision (condition last)do { … } while (condition);
Arrow from the body to outside the loopbreak;
Predefined processMethod call: average(a, b, c)

The most important of the rules is the loop translation. If there is an arrow that starts from the Yes branch of a decision box and returns to the same decision, that decision is a while condition and the boxes up to the arrow are the loop body. To find which boxes the body ends with, look at where the returning arrow leaves from.

4.2.7.2Sum from 1 to n in Java

YesNoStartread nsum = 0, i = 1i <= n ?sum = sum + ii = i + 1print sumEnd
Figure 4.2.28: The diagram to be translated into Java: sum from 1 to n.
public static void main(String[] args) {
    int n = 3;
    int sum = 0, i = 1;
    while (i <= n) {
        sum = sum + i;
        i = i + 1;
    }
    System.out.println(sum);
}

The translation is done box by box from top to bottom:

  1. The Start symbol is the beginning of the method: main opens.
  2. “read n” is an input symbol. To keep the example short, the input is taken as a constant: int n = 3;. If reading from the keyboard is wanted, this line becomes int n = in.nextInt();.
  3. The process symbol “sum = 0, i = 1” gives the starting values of two variables: int sum = 0, i = 1;.
  4. From the decision i <= n ?, the Yes branch goes to two boxes and an arrow returns to the decision. This is a loop: while (i <= n).
  5. The two rectangles on the Yes branch are the loop body. Both are written inside the braces, in the order shown in the diagram.
  6. The returning arrow is the closing brace of the body block. Execution returns from there to the condition.
  7. The output symbol “print sum” on the No branch is outside the loop: System.out.println(sum);.
  8. The End symbol is the end of the method.

When the program is run for n = 3, execution follows the same path as the diagram, step by step. The first try of the condition, 1 <= 3, is true; sum = 0 + 1 = 1 and i = 2. Then sum becomes 3 and 6. When i = 4, 4 <= 3 is false; the No path is followed and execution leaves the loop block. 6 is printed on the screen. The result is also verified by the formula: 3 × 4 / 2 = 6.

YesNoStartread nsum = 0, i = 1i <= n ?sum = sum + ii = i + 1print sumEnd YesNoStartread nsum = 0, i = 1i <= n ?sum = sum + ii = i + 1print sumEnd
Figure 4.2.29: The code counterpart of the decision symbol. (a) First try: while (i <= n), 1 <= 3 is true; the body is entered. (b) Last try: 4 <= 3 is false; the No path leaves the loop block.

At the end of the translation, every symbol has a code counterpart and every line of code has a symbol counterpart. This one-to-one correspondence is the easiest way to check that the diagram has been translated correctly. If there is a symbol with no counterpart in the program, or a line with no counterpart in the diagram, something is missing or extra in the translation.

Common mistake

Writing one of the body boxes outside the loop block. If while (i <= n) { sum = sum + i; } i = i + 1; is written, the counter's increment is left outside the loop. i never changes, the condition always comes out true, and the program enters an infinite loop. In the diagram, every box on the Yes branch, up to the last box before the returning arrow leaves, is inside the braces.

4.2.7.3Modular diagrams with a subprocess

As diagrams grow, they no longer fit on a single page. It also happens that a job is repeated in several places. In that case part of the work is drawn as a separate diagram and called from the main diagram.

Definition 4.2.19

A subprocess is a separately drawn diagram referred to by a name. In the main diagram it is called with the predefined process symbol. When the subprocess ends, the flow continues in the main diagram from the point where it was called. In Java every subprocess becomes a method.

Main diagramSubprocessStartread a, b, cavg = Average(a, b, c)print avgEndAverage(x, y, z)t = x + y + zReturn t / 3call: x=70, y=85, z=91return: 82
Figure 4.2.30: The main diagram calls the subprocess, and the subprocess returns a value. For a = 70, b = 85, c = 91, Average(70, 85, 91) is called and 82 is returned.

The sub-diagram in Figure 4.2.30 begins not with Start but with its name and parameters, “Average(x, y, z).” It ends not with End but with “Return.” Parameters are the values the subprocess receives from the place it is called. In the box avg = Average(a, b, c) the main diagram sends the values of a, b, and c to x, y, and z. For a = 70, b = 85, c = 91, the subprocess computes t = 70 + 85 + 91 = 246 and returns 246 / 3 = 82. The main diagram writes this value into the variable avg and continues from the next box.

A subprocess has two benefits. First, the same subprocess can be called from many places but is drawn only once. If an error is found in the average computation, it is fixed in a single place. Second, the main diagram becomes shorter and says “what is done”; “how it is done” stays in the sub-diagram.

import java.util.Scanner;

public class Subprocess {
    // subprocess: Average(x, y, z)
    static int average(int x, int y, int z) {
        int t = x + y + z;
        return t / 3;                     // Return t / 3
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
        int avg = average(a, b, c);       // predefined process symbol
        System.out.println(avg);
    }
}

The line static int average(int x, int y, int z) is the heading of the sub-diagram: the method's name, its three parameters, and the type of the value it returns (int). The line return t / 3; is the counterpart of the Return symbol. With the input 70 85 91 the program prints 82.

Common mistake

Forgetting integer division. In Java the quotient of two integers is also an integer; the fractional part is discarded. For 70, 85, 91 the sum 246 divides exactly by 3, so there is no visible problem. For 50, 60, 71 the sum is 181; the true average is about 60.33, but the program prints 60. If a fractional result is needed, the method must return double and the division must be written t / 3.0.

4.2.8Verification

That a diagram is correct is tested by executing it by hand on a few inputs. Which inputs to choose is not arbitrary. A small number of well-chosen inputs catch more errors than a large number of badly chosen ones.

4.2.8.1Testing a flowchart

Definition 4.2.20

A test case is a pair of an input and the output expected for it. The diagram is executed with the input and the output found is compared with the expected one. A boundary value is an input at the point where the answer to a condition changes; for example, 60 for grade >= 60.

Test inputs are chosen by five rules:

  1. A normal input is chosen and the arrows are followed step by step.
  2. Inputs are chosen that run every exit of every decision. Every box in the diagram must run at least once.
  3. Boundary values are tried separately.
  4. For each loop, cases are tried in which the body runs zero, one, and many times.
  5. Paths that do not return to the beginning or do not reach End are looked for.
YesNoStartread gradegrade >= 60 ?print "Fail"print "Pass"End YesNoStartread gradegrade >= 60 ?print "Fail"print "Pass"End YesNoStartread gradegrade >= 60 ?print "Fail"print "Pass"End
Figure 4.2.31: Testing the Pass/Fail diagram. (a) Normal input grade = 72: the Yes path. (b) grade = 45: the No path; now every box has been tried at least once. (c) Boundary value grade = 60: 60 >= 60 is true, “Pass.”

Figure 4.2.31 shows the rules applied to the Pass/Fail diagram. 72 is a normal input and runs the Yes path. 45 runs the other branch; with the two inputs every box has been tried. 60 is the boundary value and would be the only input to expose the error had > been written instead of >= in the decision box.

The reason for rule 4 on loops is this: loop errors often hide at the ends. If the accumulator's starting value is wrong, this shows most clearly in the case where the body never runs. A </<= mix-up in the condition usually causes one iteration too few or too many and is easy to notice in a one-iteration case. Table 4.2.20 gives these three cases for the sum-from-1-to-n diagram.

Table 4.2.20: Loop tests for the sum-from-1-to-n diagram. The expected value comes from the formula, the output from executing the diagram.
nCaseHow many times the body runsExpected (n(n+1)/2)Output of the diagram
0zero repetitions000
1one repetition111
5many repetitions51515

In all three rows the output equals the expected value. Had the condition been mistakenly written i < n, then for n = 1 the body would never run and 0 would be printed; for n = 5, 1 + 2 + 3 + 4 = 10 would be printed. The error shows immediately on two of the three inputs. A negative n is an invalid input. The diagram prints 0 in this case too; whether this is the desired behavior depends on the problem definition.

4.2.8.2Hand tracing with a trace table

The trace table has been used often in this chapter. The pattern can be summed up briefly: each variable is a column and each iteration is a row; the result of the decision is also written in a separate column. A table is indispensable especially in algorithms where variables change in a mutually dependent way. Euclid's algorithm is a nice example.

Euclid's algorithm finds the greatest common divisor (GCD) of two numbers. The idea is this: the common divisors of a and b are the same as the common divisors of b and the remainder of a divided by b. So the pair (a, b) is replaced by the pair (b, a % b). The remainder shrinks on every iteration and finally becomes 0. At that moment a is the GCD we are looking for.

YesNoread a, bb != 0 ?k = a % ba = bb = kprint a
Figure 4.2.32: Euclid's algorithm: until b is zero, k = a % b, a = b, b = k are done; at the end a is printed.
Table 4.2.21: Trace table of Euclid's algorithm for (48, 18). The last column is the next decision asked with the values in that row.
Stateabkb != 0 ?
start4818—18 != 0 → true
Iteration 118121212 != 0 → true
Iteration 212666 != 0 → true
Iteration 36000 != 0 → false

Initially a = 48, b = 18 and 18 != 0 is true. In the first iteration k = 48 % 18 = 12 (48 = 2 × 18 + 12); a = 18, b = 12. In the second iteration k = 18 % 12 = 6; a = 12, b = 6. In the third iteration k = 12 % 6 = 0; a = 6, b = 0. The decision 0 != 0 is false; the loop is exited and 6 is printed. GCD(48, 18) = 6. Check: 48 = 8 × 6, 18 = 3 × 6, and 8 and 3 have no common divisor greater than 1.

The loop ran 3 iterations and the decision was asked 4 times: as in every pre-test loop, the decision ran one more time than the body. The table also shows the importance of order in the diagram. What would happen if the boxes a = b and b = k in the body were swapped, that is, if b = k were done first and then a = b?

Table 4.2.22: Trace for (48, 18) when b = k and a = b are swapped in the body.
Stateabkb != 0 ?
start4818—18 != 0 → true
Iteration 112121212 != 0 → true
Iteration 20000 != 0 → false

In the first iteration b becomes 12, and then with a = b, a also becomes 12. a has taken b's new value, not its old one. In the second iteration 12 % 12 = 0 is found and both become 0. The result comes out 0 instead of 6. This is the same error as the swap error in Example 4.2.2: an assignment has erased a value that was needed later.

import java.util.Scanner;

public class Euclid {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt(), b = in.nextInt();
        while (b != 0) {
            int k = a % b;
            a = b;
            b = k;
        }
        System.out.println(a);
    }
}

The program prints 6 for (48, 18), 6 for (270, 192), and 12 for (36, 84). The algorithm works even when a < b. For (18, 48), in the first iteration 18 % 48 = 18 is found and a and b are swapped; the result is again 6.

4.2.8.3Common mistakes

The mistakes students make most often in flowcharts can be reduced to a few patterns. Table 4.2.23 collects drawing mistakes and Table 4.2.24 logic mistakes.

Table 4.2.23: Drawing mistakes.
MistakeResultFix
Unlabeled decision pathIt is unclear which condition selects itWrite Yes/No
Counter that is not updatedInfinite loopAdd the counter step
Unconnected symbolThe flow breaksConnect with an arrow
Many operations in one symbolReadability suffersSplit into steps
YesNoi = 1i <= 3 ?print iEnd YesNoi = 1i <= 3 ?print ii = i + 1End
Figure 4.2.33: A counter that is not updated. (a) Faulty: i stays 1, the screen shows 1 1 1 1 … and End is never reached. (b) Correct: when i = i + 1 is added, 1 2 3 is printed, then we go to End.

Figure 4.2.33 shows the most dangerous drawing mistake. In the diagram on the left, there is no box on the path of the returning arrow that changes i. The condition gives the same answer every time and the loop never ends. When a loop is drawn, the first question to ask is: which box on the repeat path will someday make the condition false?

Table 4.2.24: Logic mistakes, their symptoms, and their fixes.
MistakeSymptomFix
Accumulator is reset inside the loopFor 4, 7, 2, 2 is printed instead of 13: only the last value survivesMove the sum = 0 box to before the loop
Returning arrow skips the read boxThe same x is processed over and over; the sentinel never arrivesThe arrow returns to the front of the read box
Assignment in a decision box: x = 0 ?Unclear whether it is a question or an assignmentWrite a comparison: x == 0 ?
Sentinel is tested after processing−1 is added to the sum and the counter is one too highAsk the decision before adding and counting
Wide condition first in a decision chainThe lower branches never runOrder from narrow to wide
Only one arrow leaves a decisionThe flow breaks in the other caseDraw both exits, write Yes/No
No zero check before dividingDivision by 0 if no data is enteredAdd a count > 0 ? decision

Most of the mistakes in the table were shown with trace tables in the earlier sections of this chapter. What they have in common is that all are noticed immediately when the diagram is executed by hand on at least one suitable input. The accumulator mistake shows up with the input 4, 7, 2, the sentinel mistake with 80, 64, 90, −1. The chain-order mistake is exposed by −5, and the missing zero check by an input consisting of −1 alone. Executing a diagram on a few well-chosen inputs after drawing it is the most effective safeguard against all of these mistakes.

4.2.9Summary

  • A flowchart shows the steps of an algorithm with standard symbols and the order of execution with arrows. It is independent of the programming language; it lets us discuss the logic before the code and see errors early.
  • There are five basic symbols: start/end (oval), process (rectangle: computation, assignment), decision (diamond: a Yes/No question), input/output (parallelogram: read, print), and the arrow. Paths merge at a connector. Additional symbols (off-page connector, predefined process, preparation, document, data store, annotation) are used in large diagrams.
  • A decision symbol gets a question, a process symbol a command. Assignment (=) and the equality question (==) are different.
  • A good diagram flows from top to bottom, labels the decision exits, and does one job per box. The same algorithm can also be described in pseudocode; the two notations translate into each other line by line.
  • According to the Böhm–Jacopini theorem, every algorithm can be written with only the structures of sequence, selection, and repetition. Each structure has a single entry and a single exit; that is why structures can be nested.
  • In sequential flow, every box runs exactly once and in order. The order of the boxes changes the result; a swap needs a temporary variable.
  • In conditional flow, only one of the branches is followed on each run. With many options, decisions are arranged as a decision chain, from the narrow condition to the wide one; n options need n − 1 decisions. In a compound condition, AND and OR, written && and || in Java, are evaluated with short-circuit evaluation.
  • In repetitive flow, the returning arrow forms the loop. In a pre-test loop the decision runs one more time than the body; if there is no operation on the repeat path that changes the condition, an infinite loop results.
  • The counter holds the number of iterations and the accumulator the partial result; the accumulator starts at 0 for a sum and 1 for a product, before the loop. A sentinel value is a value that cannot occur in the real data; its decision is asked before the boxes that process the data.
  • In a nested loop, the inner loop runs from the start on every iteration of the outer loop; the inner body runs n × m times. In a post-test loop (do-while), the body runs at least once. for is a pre-test loop that gathers initialization, condition, and update on one line.
  • An early exit (break) adds a second exit to a loop; if a single exit is wanted, a flag is used. Continue (continue) only skips the rest of that iteration.
  • A diagram is translated into Java symbol by symbol: read → nextInt(), process → assignment, decision → if, decision + returning arrow → while, print → println, subprocess → method.
  • A diagram is tested with inputs that run every exit of every decision, with boundary values, and with cases where the loop runs zero, one, and many times. In a trace table, each variable is a column and each iteration a row.

4.2.10Key terms

The key terms of this chapter are listed below.

  • flowchart
  • terminal symbol
  • process symbol
  • decision symbol
  • input/output symbol
  • flow line
  • connector
  • off-page connector
  • predefined process
  • preparation
  • assignment
  • variable
  • condition
  • pseudocode
  • structured programming
  • spaghetti code
  • sequential flow
  • temporary variable
  • conditional flow
  • branch
  • multi-way decision
  • compound condition
  • short-circuit evaluation
  • remainder
  • repetitive flow
  • loop
  • loop body
  • iteration
  • pre-test loop
  • post-test loop
  • infinite loop
  • counter
  • accumulator
  • counter-controlled loop
  • sentinel value
  • sentinel-controlled loop
  • nested loop
  • input validation
  • early exit
  • flag
  • continue
  • subprocess
  • method
  • test case
  • boundary value
  • trace table
  • greatest common divisor (GCD)

4.2.11Test Yourself

  1. Which symbol is each of the following steps drawn with? (a) avg = sum / 3 (b) Is the number negative? (c) Print the result on the screen. (d) Use the “Compute grade average” process drawn on a separate page.

    Answer

    (a) is an assignment: process symbol, rectangle. (b) is a question whose answer is yes or no: decision symbol, diamond; x < 0 ? is written inside. (c) gives data to the outside: input/output symbol, parallelogram. (d) calls a separately drawn subprocess: predefined process symbol, a rectangle with vertical lines on its sides.

  2. A sequential diagram reads a = 5, then runs the boxes b = a * 2, a = b + a, c = a + b in order and prints a, b, and c. What are the variables after each box, and what is the output?

    Answer

    b = a * 2: b = 5 × 2 = 10; a = 5. a = b + a: a = 10 + 5 = 15; a's old value 5 is now gone. c = a + b: c = 15 + 10 = 25. The output is 15 10 25. When c is computed, the new value of a (15) is used.

  3. The decisions in the temperature chain are arranged in reverse order: first t < 25 ? (Yes → “Mild”), then t < 15 ? (Yes → “Cold”), then t < 0 ? (Yes → “Freezing”, No → “Hot”). What is printed for t = −5, 10, 20, and 30? Which exits can never run?

    Answer

    For −5, 10, and 20 the first decision is true and all three print “Mild.” For 30 the first decision is false. Execution reaches the second decision; 30 < 15 and 30 < 0 are false and “Hot” is printed. The “Cold” and “Freezing” branches cannot be reached with any input: the second decision is reached only when t ≥ 25, and such a t is less than neither 15 nor 0. The right order is from the narrow condition to the wide one, that is, t < 0, t < 15, t < 25.

  4. In a loop started with i = 10, the decision is i > 0 ?; on the Yes branch i is printed and i = i − 3 is done. What is the output? How many times do the body and the decision run, and what is i when the loop ends?

    Answer

    The condition is true while i is 10, 7, 4, 1, in turn; these values are printed: 10 7 4 1. After 1 is printed, i = 1 − 3 = −2 and −2 > 0 is false. The body runs 4 times and the decision 5 times; the loop is exited with i = −2.

  5. In a diagram that finds the product of the numbers from 1 to 5, the accumulator was started with product = 0; the body is product = product * i. What does the diagram print? What does the corrected diagram print?

    Answer

    In the first iteration 0 × 1 = 0, and since every later iteration multiplies by 0, the result is 0. The neutral value for a product is 1; starting with product = 1, the iterations give 1, 2, 6, 24, 120 and 120 is printed.

  6. The inputs 70, 85, 0, −1 are entered, in order, into the sentinel-controlled grade-average diagram. What do the sum, counter, and average become? What would have happened if 0 had been chosen as the sentinel instead of −1?

    Answer

    70, 85, and 0 are real grades: the sum is 70 + 85 + 0 = 155 and the counter is 3. When −1 is read the loop ends. The average is 155 / 3 ≈ 51.67. Had the sentinel been 0, the third input would have been interpreted as “data finished”: the sum would be 155, the counter 2, and the average 77.5. Because 0 can be a real grade, it is not suitable as a sentinel.

  7. In a nested loop the outer counter i runs from 1 to 3 and the inner counter j from i to 3. The inner body prints one “*”; at the end of each outer iteration a line break is printed. What is the output, and how many stars are printed in all?

    Answer

    With i = 1, j = 1, 2, 3: three stars. With i = 2, j = 2, 3: two stars. With i = 3, j = 3: one star. The output is the lines ***, **, *, one under another. In total 3 + 2 + 1 = 6 stars are printed. Because the start of the inner loop depends on the outer counter, the inner body runs 6 times, not 3 × 3 = 9.

  8. The body of a loop that starts with count = 10 prints the counter and increases it by 1; the condition is count < 5. What is printed when the loop is drawn as a pre-test (while) and as a post-test (do-while) loop?

    Answer

    In the pre-test loop the condition is asked before the body: 10 < 5 is false and the body never runs; nothing is printed. In the post-test loop the body runs first: 10 is printed and count becomes 11. Then 11 < 5 is asked, it is false, and the loop ends. The output is just 10. The two loops behave differently when the condition is false at the first try.

  9. Euclid's algorithm is executed for (84, 36). What are a, b, and k on each iteration? How many iterations does the loop run, how many times is the decision asked, and what is printed?

    Answer

    Initially: a = 84, b = 36; 36 != 0 is true. Iteration 1: k = 84 % 36 = 12 (84 = 2 × 36 + 12); a = 36, b = 12. Iteration 2: k = 36 % 12 = 0; a = 12, b = 0. 0 != 0 is false; the loop ends. 2 iterations, 3 decisions; 12 is printed. Check: 84 = 7 × 12, 36 = 3 × 12, and 7 and 3 have no common divisor greater than 1.

4.2.12Further reading

  • C. Böhm, G. Jacopini, “Flow Diagrams, Turing Machines and Languages with Only Two Formation Rules,” Communications of the ACM, 9(5), 1966: the original paper showing that every flowchart has a structured equivalent made of sequence, selection, and repetition.
  • E. W. Dijkstra, “Go To Statement Considered Harmful,” Communications of the ACM, 11(3), 1968: the two-page letter that began the structured-programming debate, arguing why statements that jump at random make programs incomprehensible.
  • R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), Section 1.3: conditionals and loops in Java, explained with trace tables and many short programs.
  • A. B. Downey, C. Mayfield, Think Java (2nd ed., O'Reilly, 2019): conditionals, logical operators, and loops explained in plain language for beginners; the online edition is free.

4.2.13References

  1. ISO 5807:1985, Information processing — Documentation symbols and conventions for data, program and system flowcharts, program network charts and system resources charts.
  2. P. Deitel, H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
  3. R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.3 Conditionals and Loops.
  4. Oracle, The Java Tutorials: Control Flow Statements.
  5. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019.

Related pages: Chapter 4.2 slides · Study questions · Flowchart Runner simulator · Glossary · © Sercan Külcü. All rights reserved.