Chapter 1.4: Flowcharts

Object Oriented Programming with Java
Algorithms and flowchartsBasic symbolsDrawing rulesSequence SelectionIterationLoop symbolSubprogramsFrom flowchart to Java
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Concept

Explain how algorithms and flowcharts relate; say why and where flowcharts are used.

Symbols

Recognize and correctly use the Start/End, Input/Output, Process, Decision, Loop, Print, connector and subprogram symbols.

Control structures

Tell sequence, selection and iteration apart; draw a flowchart for each.

Tracing

Trace a flowchart step by step on a given input to find the output; spot boundary errors and infinite loops.

From flowchart to Java

Know the Java equivalent of each symbol: nextInt(), assignment, if/else, while, for, println.

Design

Plan a simple problem (a sum, odd/even, counting) as a flowchart first, then turn it into a program.

Flowcharts

Flowcharts

  • Algorithm: a plan of step-by-step instructions for solving a problem or carrying out a task.
  • Flowchart: shows an algorithm's steps, the links between them and its control logic visually.
  • Each step is a symbol; their order is shown by arrows (flow lines).
Analogy: a recipe is an algorithm; the same recipe drawn with boxes and arrows is a flowchart. It is the easiest way to plan a solution on paper before writing a program.
StartFill the kettleWater boiling?WaitBrew the teaEndNY

Flowcharts

Benefits and Limitations

Benefits

  • Simplifies complex processes: the whole solution at a glance.
  • Helps find errors and room for improvement before any code is written.
  • Used to document and report processes.
  • Language-independent: a common language for the team.

Limitations

  • For large programs the chart grows huge and hard to read.
  • When the algorithm changes, the chart must be redrawn.
  • More detail means more symbols; then pseudocode is more practical.
problemalgorithmflowchartJava programrun, testwrong result: back to the algorithm
The usual workflow: problem → algorithm (steps) → flowchart → Java program → run and test.

Symbols and Rules

The Basic Symbols

StartStart / End

Oval. Where the algorithm begins and ends.

Read xInput / Output

Parallelogram. Reading data from the keyboard (input).

x = x + 1Process

Rectangle. Calculation, operation, assignment.

x > 0 ?Decision

Diamond. A yes/no question with two exits.

i = 1; i ≤ 5; i++Loop

Hexagon. A fixed number of repetitions.

Print xPrint

Wavy bottom edge. Writing the result to the screen or paper.

AConnector

Small circle. Where lines join.

Flow line

Arrow. The order of steps; follow its direction.

The symbols follow ISO 5807. Some sources use a parallelogram for both input and output; the "Print" symbol is also common for screen output.

Symbols and Rules

The Java Equivalent of Each Symbol

SymbolText in the chartJava
Start / EndStart … Endpublic static void main(String[] args) { … }
InputRead numint num = scanner.nextInt();
Processresult = num1 + num2int result = num1 + num2;
Decisionresult = 0 ?if (result == 0) { … } else { … }
Decision + back arrowcount ≤ 10 ?while (count <= 10) { … }
Loopi = 1; i ≤ 10; i++for (int i = 1; i <= 10; i++) { … }
PrintPrint resultSystem.out.println(result);
In a process box = means assignment; in a decision box it means comparison. Java writes assignment as = and comparison as ==. The chart's "mod" is Java's % operator.

Symbols and Rules

Other Symbols

average()Subprogram

Rectangle with double side lines. Calls a sequence of steps drawn separately. Java: a method call.

BOff-page connector

Downward-pointing pentagon. The chart continues on another page; both ends carry the same letter.

gradesData store

Cylinder. Saving to and reading from a file or database.

Read xManual input

Quadrilateral with a slanted top. Some sources draw keyboard input with it.

commentAnnotation

Open bracket. A note outside the flow. Java: a // comment.

i = 1Preparation

Hexagon. ISO 5807 calls it preparation; used to set up a loop.

The basic symbols suffice for most charts. The extra ones help split long charts (subprogram, off-page connector) and show where data is stored.

Symbols and Rules

How to Draw a Flowchart

Steps
  1. Identify the operations step by step: inputs, calculations, outputs.
  2. Place the steps in a logical order.
  3. Connect all operations with flow lines.
  4. Mark the decision points with conditions.
Drawing rules
  • Exactly one Start and at least one End.
  • The flow reads top to bottom, left to right.
  • Every symbol has one exit; only the Decision symbol has two (Y/N).
  • Decision exits are always labeled Yes/No.
  • Lines should not cross; use a connector if needed.
  • Write short, clear text in the boxes.

Symbols and Rules

Drawing Step by Step: Area of a Rectangle

StartEnd

Problem: find the area of a rectangle. First the skeleton: a Start and an End.

StartRead a, bEnd

The inputs: side lengths a and b are read from the keyboard (parallelogram).

StartRead a, barea = a × bEnd

Add the process: compute area = a × b and assign it to the area variable (rectangle).

StartRead a, barea = a × bPrint areaEnd

Add the output: print the computed area (Print).

StartRead a, barea = a × bPrint areaEnd

Connect the symbols in order with flow lines. There is no decision here: the flow is sequential.

StartRead a, barea = a × bPrint areaEnda = 4, b = 3area = 12screen: 12

Test: with a = 4, b = 3 the area is 12 and the screen shows 12. The chart works.

Control Structures

Control Structures

SequenceStep 1Step 2Step 3

Steps run in order, once each.

Selectioncondition ?PQYN

The condition decides which steps run.

Iterationcondition ?bodyYN

Some steps repeat while a condition holds.

Structured program theorem (Böhm and Jacopini, 1966): every algorithm can be written using only these three structures (sequence, selection, iteration), nested. In Java: consecutive statements, if/else, while/for.

Control Structures

Structured and Unstructured Flowcharts

Structured

StartAK ?BCDEndYN

Unstructured

StartAK ?BCL ?DEndYNYN
  • In a structured chart every control structure has one entry and one exit (dashed frame). Structures are placed one after another or nested.
  • In an unstructured chart arrows jump anywhere: L's Yes arrow enters the middle of the other branch (C), its No arrow goes back to A. Such “spaghetti” flow is hard to trace and debug.
  • Older languages wrote such jumps with goto. In Java goto is a reserved word that cannot be used.
  • break and continue are limited jumps: they only end the enclosing loop or skip to its next round.
  • By the Böhm–Jacopini theorem every chart can be made structured, using a flag variable if necessary.

Sequence

Sequential Flow

The steps (statements) are laid out one after another in a logical order. The flow runs top to bottom.

StartRead a, bc = a + bPrint cEnd
Simple

A plain, easy-to-follow flow with no branching or repetition.

Easy to maintain

Easy to debug and understand: the steps are traced in the order written.

Order matters

A step that uses an earlier result cannot move before it. Independent steps (e.g. two separate reads) can be swapped.

No going back

Each step runs exactly once; no step is revisited or skipped.

Wrong order: if result = num1 + num2 comes before the numbers are read, the sum uses values that are not yet known. In Java the compiler catches variables declared but never assigned: variable num1 might not have been initialized.

Sequence

Example: The Sum of Two Numbers

Problem: print the sum of two numbers entered at the keyboard.

Algorithm

  1. Start
  2. Read the first number (num1)
  3. Read the second number (num2)
  4. Add them and assign to result
  5. Print result
  6. End

Each algorithm step corresponds to one symbol in the chart.

StartRead num1Read num2result = num1 + num2Print resultEnd

Sequence · Code trace

From Flowchart to Java: The Sum Program

import java.util.Scanner;

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

The program starts at main (Start). A Scanner is created to read the keyboard.

StartRead num1Read num2result = num1 + num2Print resultEnd

The prompt prints and the user enters 7: nextInt() assigns it to num1.

StartRead num1Read num2result = num1 + num2Print resultEnd

The user enters 5: num2 = 5.

StartRead num1Read num2result = num1 + num2Print resultEnd

Process box: result = 7 + 5 = 12.

StartRead num1Read num2result = num1 + num2Print resultEnd

Print box: println writes the result.

StartRead num1Read num2result = num1 + num2Print resultEnd

The Scanner is closed and main ends (End). Every line ran exactly once.

Selection

Conditional Flow

A flow in which one of two (or more) alternatives is chosen.

  • Decision point (K): a condition whose answer is Yes or No.
  • Yes branch (P): if the answer is yes, go on to P.
  • No branch (Q): if the answer is no, go on to Q.
  • It gives flexibility (different behavior in different situations), decision making (actions that depend on a condition) and control (check the state, act on it).
if (K) {
    P;   // condition true
} else {
    Q;   // condition false
}
K: condition ?PQnext stepYesNo

Selection

Example: Is the Number Odd or Even?

Problem: print whether a given number is odd or even.

  1. Start
  2. Read the number
  3. Compute number mod 2, assign to result
  4. If result is 0 go to 5, else go to 6
  5. Print "even", go to 7
  6. Print "odd"
  7. End
mod: the remainder. 7 mod 2 = 1, 8 mod 2 = 0. An even number leaves remainder 0 when divided by 2. In Java: num % 2.
StartRead numresult = num mod 2result = 0 ?Print evenPrint oddEndYN

Selection · Code trace

From Flowchart to Java: Odd or Even?

import java.util.Scanner;

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

Start: a Scanner is created.

StartRead numresult = num mod 2result = 0 ?Print evenPrint oddEndYN

The user enters 7: num = 7.

StartRead numresult = num mod 2result = 0 ?Print evenPrint oddEndYN

result = 7 % 2 = 1 (7 = 3 × 2 + 1).

StartRead numresult = num mod 2result = 0 ?Print evenPrint oddEndYN

Decision: 1 == 0 is false → the No (N) path, the else block.

StartRead numresult = num mod 2result = 0 ?Print evenPrint oddEndYN

"odd" is printed. Line 10 in the if block was skipped.

StartRead numresult = num mod 2result = 0 ?Print evenPrint oddEndYN

The two paths meet at End. With 8, result = 0 and the Y path would print "even".

Selection

Nested Decisions: Positive, Negative, Zero

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYN

With three outcomes, chain two decision boxes: the first one's No exit leads to the second.

int num = scanner.nextInt();
if (num > 0) {
    System.out.println("positive");
} else if (num < 0) {
    System.out.println("negative");
} else {
    System.out.println("zero");
}
inputpath takenoutput
5decision 1 Ypositive
−2decision 1 N, decision 2 Ynegative
0decision 1 N, decision 2 Nzero

One-way decision (Yes branch only): in Java, an if without else.

Selection · Code trace

Nested Decisions: Code Trace

Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
if (num > 0) {
    System.out.println("positive");
} else if (num < 0) {
    System.out.println("negative");
} else {
    System.out.println("zero");
}
StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYNinput: −4

Run 1: the user enters −4, num = −4.

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYN−4 > 0 → false

Decision 1: -4 > 0 is false → No exit.

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYN−4 < 0 → true

The No exit leads to decision 2: -4 < 0 is true → Yes.

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYNoutput: negative

negative is printed; the else branch is skipped and the flow goes to End.

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYNinput: 0

Run 2: this time the user enters 0 (the output panel shows the new run).

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYN0 > 0 → false

0 > 0 is false: 0 is not positive.

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYN0 < 0 → false

0 < 0 is false too → the second decision's No exit.

StartRead numnum > 0 ?positivenum < 0 ?negativezeroEndYNYNoutput: zero

Both conditions are false: the last else runs and prints zero. Exactly one of the three branches runs each time.

Selection

Compound Conditions: AND, OR

age ≥ 18 ?license ?can drivecan't driveage ≥ 18 ANDlicense ?can drivecan't driveYYNNYN=
agelicenseage ≥ 18 AND licenseage ≥ 18 OR license
20yesYes → can driveYes
20noNo → can't driveYes
16yesNo → can't driveYes
16noNo → can't driveNo
  • AND: Yes only if both conditions are true. Drawn as two decisions, the first one's No exit goes straight to “can't drive”; the second is never asked.
  • OR: one true condition is enough. Drawn as two decisions, the first one's Yes exit goes straight to the result.
  • Java: if (age >= 18 && license), ||. Java, too, checks the second condition only when needed.

Iteration

Iteration (Loops)

A flow in which steps repeat more than once. In the chart, an arrow leads back to the decision box.

?Condition-controlled loop

Repeats while a condition holds. The number of rounds may be unknown in advance (e.g. read until the user enters 0). Java: while.

i=1..1010 timesCounted loop

The number of repetitions is known up front (e.g. 1 to 10). Java: for.

?∞Infinite loop

The condition always holds, so the steps repeat forever. Usually a bug; used on purpose in always-on programs such as servers.

  • Efficient: the same operation runs as often as needed without rewriting the code.
  • Dynamic: the number of repetitions can depend on the input; the program adapts.
  • Avoids repeated code: printing 1000 numbers takes 3–4 lines, not 1000.

Iteration

Example: Printing the Numbers 1 to 10

Algorithm

  1. Start
  2. count = 1
  3. If count ≤ 10 go to 4, else go to 7
  4. Print count
  5. Add 1 to count
  6. Go to 3
  7. End
Step 6, "Go to 3", is the back arrow returning to the top of the decision box. That arrow makes the loop; the decision box is its exit door.
Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Iteration · Code trace

From Flowchart to Java: the while Loop

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

count = 1: the loop variable gets its initial value.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 1 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

1 is printed and count becomes 2; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 2 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

2 is printed and count becomes 3; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 3 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

3 is printed and count becomes 4; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 4 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

4 is printed and count becomes 5; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 5 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

5 is printed and count becomes 6; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 6 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

6 is printed and count becomes 7; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 7 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

7 is printed and count becomes 8; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 8 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

8 is printed and count becomes 9; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 9 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

9 is printed and count becomes 10; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 10 <= 10 is true → Yes, enter the loop body.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

10 is printed and count becomes 11; the back arrow returns to the condition.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

Condition: 11 <= 10 is false → No, leave the loop.

Startcount = 1count ≤ 10 ?Print countcount += 1EndYN

End. The body ran 10 times, the condition 11 times.

Iteration

Boundary Condition: < or ≤?

A single character in the loop condition changes the number of rounds. The counter starts at 1 and goes up by 1 each round:

ConditionBody runsOutputPrints 1 to 10?
count < 1091 2 3 4 5 6 7 8 9No: 10 missing
count <= 10101 2 3 4 5 6 7 8 9 10Yes
count < 11101 2 3 4 5 6 7 8 9 10Yes (same meaning)
count <= 11111 2 … 10 11No: extra 11
This is an off-by-one error. To avoid it, test the condition with the last value: is it true when the counter is 10? "1 through 10" includes 10, so the condition must be count ≤ 10.

Iteration

A Dedicated Loop Flow (the Loop Symbol)

The same problem: print the numbers 1 to 10.

  1. Start
  2. Loop: 1 to 10
  3. Print the loop variable
  4. End of loop
  5. End

The hexagon gathers the three parts of the loop in one box:

  • initialization: i = 1 (once)
  • condition: i ≤ 10 (before each round)
  • update: i++, i.e. add 1 to i (after each round)

The small circle marked "i" is the end of the loop: the flow returns from there to the hexagon, and goes on to End when the loop is done.

Starti = 1; i ≤ 10; i++Print iiEndrepeatdone

Iteration

A Decision Inside a Loop: Counter and Accumulator

Startpassed = 0sum = 0k = 1; k ≤ 5; k++Read gradesum += gradegrade ≥ 50 ?passed += 1kPrint passed, sum / 5EndYNrepeatdone
int passed = 0, sum = 0;
for (int k = 1; k <= 5; k++) {
  int grade = scanner.nextInt();
  sum += grade;
  if (grade >= 50) {
    passed++;
  }
}
System.out.println(passed + " passed, average "
    + sum / 5.0);
Input 45 70 50 30 88 → Output 3 passed, average 56.6
  • Counter (passed): goes up by 1 when the condition holds. Accumulator (sum): gains a value every round.
  • The decision is inside the loop: it is tested again with each new grade. The No branch skips the counter and goes to the end of the loop.
  • 50 is on the boundary: with >= a 50 passes; with > the count would be 2.
  • sum / 5.0: with 5, integer division would give 56.
  • A third pattern is the flag: a boolean variable that records whether something happened (found = true).

Iteration

Sentinel-Controlled Loops

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN
  • Sentinel value: a special value that marks the end of input and is not counted as data (0, −1, “end”).
  • The number of values is unknown in advance: the loop is condition-controlled, a while in Java.
  • Priming read: read the first value before the loop and the next one at the end of the body. Then the condition sees the sentinel at once and it never joins the sum.
  • Pick a sentinel that cannot occur in real data: for grades −1 works, 0 does not (a student may score 0).
  • After the loop, check count = 0 separately: if no numbers were entered, sum / count divides by zero (an ArithmeticException for integers, NaN for double).

Iteration · Code trace

Sentinel Loop: Code Trace

int sum = 0, count = 0;
int num = scanner.nextInt();
while (num != 0) {
  sum += num;
  count++;
  num = scanner.nextInt();
}
if (count > 0) {
  System.out.println("Average: "
      + (double) sum / count);
} else {
  System.out.println("No numbers");
}
Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYNsum = 0, count = 0

The accumulator and counter start at zero.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYNnum = 12

Priming read: the first number is read before the loop. Input: 12 7 5 0.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN12 ≠ 0 → Y

Condition: 12 ≠ 0 is true → Yes, enter the body.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYNsum = 12, count = 1, num = 7

sum = 12, count = 1; the next number is read at the end of the body: 7.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN7 ≠ 0 → sum = 19, count = 2

Back to the decision: 7 ≠ 0. sum = 19, count = 2; reads 5.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN5 ≠ 0 → sum = 24, count = 3

5 ≠ 0: sum = 24, count = 3; reads 0, the sentinel.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN0 ≠ 0 → N

0 ≠ 0 is false → No: leave the loop. The 0 never joined the sum.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN3 > 0 → Y

Check after the loop: count = 3 > 0 → Yes.

Startsum = 0count = 0Read numnum ≠ 0 ?sum += numcount += 1Read numcount > 0 ?Print sum/ countPrint"No numbers"EndYNYN24 / 3 = 8.0

24 / 3 = 8.0 is printed. Had the first number been 0, the No branch would print No numbers.

Iteration

Leaving a Loop Early

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreak
  • Once a search finds its target, the remaining rounds are pointless: a second decision inside the loop takes the flow out of it.
  • The loop has two exits in the chart: when the condition turns false (not found) and when the target is found. Both paths meet at the Print pos box.
  • In Java the second exit is break; it ends only the loop it is in.
  • pos = 0 means “not found”; positions start at 1, so it cannot be mistaken for a real one.
  • The structured, single-exit version uses a flag:
int pos = 0;
boolean found = false;
for (int i = 1; i <= 5 && !found; i++) {
  int x = scanner.nextInt();
  if (x < 0) {
    pos = i;
    found = true;
  }
}

Iteration · Code trace

Early Exit: Code Trace

int pos = 0;
for (int i = 1; i <= 5; i++) {
  int x = scanner.nextInt();
  if (x < 0) {
    pos = i;
    break;
  }
}
System.out.println("Position: " + pos);
Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreakpos = 0, i = 1

pos = 0 (none found yet), i = 1. Input: 4 9 −2 6 1.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreak1 ≤ 5 → Y

1 ≤ 5 → Yes, enter the body.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreakx = 4: 4 < 0 → N

x = 4; 4 < 0 is false → No.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreaki = 2: 2 ≤ 5 → Y

i = 2; back to the decision: 2 ≤ 5 → Yes.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreakx = 9: N; i = 3: Y

x = 9 is again non-negative; i = 3, 3 ≤ 5 → Yes.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreakx = −2: −2 < 0 → Y

x = −2; −2 < 0 is true → Yes branch.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreakpos = 3

pos = 3. break: i += 1 and the condition are skipped and the loop ends at once; 6 and 1 are never read.

Startpos = 0i = 1i ≤ 5 ?Read xx < 0 ?i += 1pos = iPrint posEndYNYNbreakPosition: 3

The result is printed. With no negative input, the loop would exit through No at i = 6 and print Position: 0.

Iteration · Code trace

Nested Loops: Code Trace

for (int i = 1; i <= 2; i++) {
  for (int j = 1; j <= 3; j++) {
    System.out.print(i * j + " ");
  }
  System.out.println();
}
Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonei = 1

The outer loop starts: i = 1; 1 ≤ 2 is true.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonej = 1

The inner loop starts: j = 1.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedone1 × 1 = 1

1 × 1 = 1 is printed.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonej = 2: 1 × 2 = 2

End of loop j: the repeat arrow leads back to the inner loop. j = 2, prints 2.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonej = 3: 1 × 3 = 3

j = 3, prints 3.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonej = 4: 4 ≤ 3 → done

j = 4: 4 ≤ 3 is false, the inner loop ends (the done arrow). println starts a new line.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonei = 2, j = 1: 2

End of loop i: back to the outer loop, i = 2. The inner loop starts again from j = 1: prints 2.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonej = 2, 3: 4 and 6

j = 2 and 3: prints 4 and 6.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedoneinner loop done

The inner loop ends again; new line.

Starti = 1; i ≤ 2; i++j = 1; j ≤ 3; j++Print i × jjNew lineiEndrepeatrepeatdonedonei = 3: 3 ≤ 2 → done

i = 3: the outer loop ends. The inner body ran 2 × 3 = 6 times, println twice.

Subprograms

The Subprogram Symbol and Methods

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYN
  • A long chart is split into meaningful parts: a part is drawn as a separate chart and called from the main chart with the subprogram symbol.
  • The subprogram's Start box carries its name and inputs (parameters); it ends with a Return box.
  • On a call the flow moves into the subprogram; at Return the result goes back to the caller and the flow continues right after the call (dashed arrows).
  • In Java it is a method: static double average(int mid, int fin), called as average(mid, fin). final is a Java keyword, so the variable is named fin.
  • The payoff: no redrawing the same steps, each part tested on its own, a short main chart.

Subprograms · Code trace

A Subprogram Call: Code Trace

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

The program starts at main (Start).

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYNmid = 40, fin = 70

The user enters 40 and 70 on one line.

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYNaverage(40, 70) called

Subprogram box: average is called; 40 and 70 are copied into the parameters.

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYNavg = 16 + 42 = 58.0

The subprogram's own chart runs: 16 + 42 = 58.0. This avg is a local variable, separate from the avg in main.

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYNReturn 58.0

Return: the value goes back to the caller; average's frame is popped off the stack.

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYN58.0 ≥ 50 → Y

The flow continues after the call: 58.0 ≥ 50 is true → Yes.

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYN58.0 passed

The Yes branch prints.

StartRead mid, finavg = average(mid, fin)avg ≥ 50 ?Print avg, "passed"Print avg, "failed"Endaverage(mid, fin)avg = mid × 0.4+ fin × 0.6Return avgYNEnd

End. The same subprogram can be called again with other inputs: for 45 and 30, 36.0 failed.

Practice

Practice: The Sum 1 to n

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYN

Sequence (reading, initial values), iteration (adding) and sequence again (printing) together. sum is an accumulator: it starts at 0 and grows each round.

System.out.print("n: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;
while (i <= n) {
    sum += i;
    i += 1;
}
System.out.println("Sum: " + sum);
i123456
sum136101515 (exit)

For n = 5 the output is Sum: 15 (1 + 2 + 3 + 4 + 5).

Practice · Code trace

The Sum 1 to n: Code Trace

System.out.print("n: ");
int n = scanner.nextInt();
int sum = 0;
int i = 1;
while (i <= n) {
    sum += i;
    i += 1;
}
System.out.println("Sum: " + sum);
StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYNn = 4

The prompt prints and the user enters 4: n = 4.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYNsum = 0, i = 1

Initial values: accumulator sum = 0, counter i = 1.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYN1 ≤ 4 → Y

Condition: 1 ≤ 4 is true → Yes, enter the body.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYNsum = 0 + 1 = 1, i = 2

sum = 0 + 1 = 1, i = 2; back to the decision.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYN2 ≤ 4 → sum = 3, i = 3

2 ≤ 4 is true: sum = 1 + 2 = 3, i = 3.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYN3 ≤ 4 → sum = 6, i = 4

3 ≤ 4 is true: sum = 3 + 3 = 6, i = 4.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYN4 ≤ 4 → sum = 10, i = 5

4 ≤ 4 is true: sum = 6 + 4 = 10, i = 5.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYN5 ≤ 4 → N

Condition: 5 ≤ 4 is false → the No exit, leave the loop.

StartRead nsum = 0i = 1i ≤ n ?sum += ii += 1Print sumEndYNoutput: Sum: 10

The result is printed: 1 + 2 + 3 + 4 = 10. The body ran 4 times, the condition 5 times.

Practice

Desk Checking: The Trace Table

num = 472sum = 0num > 0 ?sum += num mod 10num = num / 10Print sumYN
Stepnum mod 10sumnumnum > 0 ?
start–0472Y
round 12247Y
round 2794Y
round 34130N → Print 13
  • Desk check: trace the chart or code on paper with one input, no computer.
  • Trace table: one column per variable, one row per round. The condition column shows how often the loop ran: 3 rounds, 4 tests.
  • num / 10 is integer division: 47 / 10 = 4. Digits are taken right to left.
  • The table exposes errors early: forget the num = num / 10 box and the column stays 472 forever, an infinite loop.
int num = 472, sum = 0;
while (num > 0) {
  sum += num % 10;
  num /= 10;
}
System.out.println(sum);

Practice

Testing a Flowchart: Test Cases

Positive / negative / zero chart

InputWhy this one?Expected
5Yes path of decision 1positive
−2Yes path of decision 2negative
0No path of both decisionszero
1 and −1either side of the boundarypositive, negative

Sum 1 to n chart

nWhy this one?Expected
0body never runsSum: 0
1one roundSum: 1
4typical caseSum: 10
−3invalid inputSum: 0 (is that what we want?)
  • One input is not enough: every exit of every decision box should run at least once (path coverage).
  • Boundary values sit on either side of where the condition flips: 0 and 1 for num > 0; 49 and 50 for grade ≥ 50. Off-by-one errors show up here.
  • For loops, three cases: inputs that make it run zero times, once and many times.
  • Work out the expected output by hand before running, then compare. Any difference means an error in the chart, the code or the expectation.

Practice

Ways to Express an Algorithm

NotationOdd/even exampleStrengthWeakness
Plain language"Read the number; if dividing by 2 leaves 0, print even, otherwise odd."Anyone can read itCan be ambiguous
FlowchartRead → Process → Decision → Print even / Print oddShows the flow visually; branches and loops are easy to seeUnwieldy for large problems
PseudocodeREAD n; IF n mod 2 = 0 THEN PRINT "even" ELSE PRINT "odd"Quick to write, close to codeNo standard syntax
Javaif (num % 2 == 0) … else …A computer can run itMust follow strict syntax
In software engineering the modern counterpart of the flowchart is the UML activity diagram: same idea, with a filled circle for the start, a diamond for decisions and rounded boxes for activities.

Practice

Tools for Drawing Flowcharts

ToolWhat it doesNote
Pen and paperThe fastest sketch; the only option in an examTedious to correct
draw.io (diagrams.net)Free in-browser drawing tool with ready-made flowchart symbolsDraws, does not run
Microsoft VisioCommercial diagramming program with standard symbol librariesPaid
FlowgorithmRuns the chart and tracks variables; generates code in many languages, Java includedFree, for teaching
MermaidDraws charts from text; GitHub and many Markdown tools render it directlyLives alongside the code

The odd/even chart in Mermaid

flowchart TD
  A([Start]) --> B[/Read num/]
  B --> C{num mod 2 = 0 ?}
  C -- Yes --> D[Print even]
  C -- No --> E[Print odd]
  D --> F([End])
  E --> F
  • ([ ]) Start/End, [/ /] input, { } decision, [ ] process; --> a flow line, -- Yes --> a labeled exit.
  • TD: top-down layout; the tool places the boxes itself.
  • Whatever the tool, the rules are the same: one Start, labeled decision exits, no crossing arrows.

Summary

Summary

TopicKey points
Flowchartan algorithm drawn with symbols and arrows; a language-independent plan
Symbolsoval Start/End · parallelogram input · rectangle process · diamond decision · hexagon loop · wavy box print · circle connector
Rulesone Start; top to bottom; two labeled exits (Y/N) on decisions; no crossing lines
Sequencesteps one after another, each once; dependent steps must stay in order
Selectionquestion K → Yes: P, No: Q; Java if/else; nested decisions for three or more paths
Iterationback arrow + decision; initialization, condition, update; Java while, for, do-while
Patternscounter, accumulator, flag; sentinel loop; early exit (break); subprogram = method
Pitfalls< / ≤ boundary errors; forgetting the update → infinite loop

Summary

Common Mistakes

A decision with one exitTwo arrows must leave a decision, labeled Y/N; otherwise what happens on "no" is undefined.
Wrong symbolA rectangle for keyboard input, a parallelogram for a calculation. Input = parallelogram, process = rectangle.
Using = to compareif (result = 0) does not compile: error: incompatible types: int cannot be converted to boolean. Write result == 0.
Forgetting the initial valueWithout the "count = 1" box, Java complains too: error: variable count might not have been initialized.
Forgetting the updateWithout the "count += 1" box the condition stays true: an infinite loop. The compiler cannot catch this.
Boundary errorWriting count < 10 for "1 through 10" skips 10. Test the condition with the last value.
A semicolon after the loop headerwhile (count <= 10); compiles, but the loop body is empty; the counter never grows and the program hangs.
Back arrow to the wrong placeIf the back arrow returns above the "count = 1" box, the counter resets to 1 every round: another infinite loop. It must return to the decision box.

Summary

Sample Problems

  1. Which symbols draw the steps "get the user's age", "age ≥ 18?", "tax = price × 0.2" and "print the result"?
  2. Chart: sum = 0, i = 1; while i ≤ 4, sum += i and i += 1; then Print sum. What is the output? What is i on exit?
  3. What does the odd/even chart print for −3? (What is -3 % 2 in Java?)
  4. In the 1-to-10 chart, how many numbers would print with the condition count < 10? How many times would the decision be tested?
  5. Starting from num = 1, how many times does the loop "while num < 100, num = num × 2" run, and what is num at the end?
Show answers
  1. Parallelogram (input) · diamond (decision) · rectangle (process) · Print (or an output parallelogram).
  2. Sum = 1 + 2 + 3 + 4 = 10; at i = 5, 5 ≤ 4 is false and the loop exits.
  3. -3 % 2 = −1 (in Java the remainder takes the sign of the dividend). −1 ≠ 0 → No path → prints odd. Correct, because the test is "= 0"; testing "= 1" would treat negative odd numbers as even.
  4. 1, 2, …, 9: 9 numbers. The condition is tested 10 times (count = 1…10); it is false at 10.
  5. 1 → 2 → 4 → 8 → 16 → 32 → 64 → 128: it runs 7 times, num = 128.

Summary

Exercises

  1. Draw a flowchart that reads a rectangle's sides and prints its area and perimeter (sequence).
  2. Draw a chart that finds the largest of three numbers. Trace it for 3, 9, 5.
  3. Draw a chart for the sum of the even numbers from 1 to n. What is it for n = 10?
  4. Draw a chart for n! (factorial) and translate it to Java. What is it for n = 5?
  5. Draw a chart that reads numbers until the user enters 0, then prints the sum. Input: 4 7 2 0.
  6. Draw a chart that turns a 0–100 score into a letter grade (≥ 85 A, ≥ 70 B, ≥ 50 C, else F).
Answers / hints
  1. Start → Read a, b → area = a × b → perimeter = 2 × (a + b) → Print area, perimeter → End. No decisions.
  2. max = a; if b > max then max = b; if c > max then max = c; Print max. Two one-way decisions. 3, 9, 5 → 9.
  3. sum = 0, i = 2; while i ≤ n, sum += i, i += 2. n = 10 → 2 + 4 + 6 + 8 + 10 = 30.
  4. f = 1 (not 0!); for i = 1 to n: f = f × i. for (int i = 1; i <= n; i++) f *= i; → 120.
  5. Read a number first; while num ≠ 0, sum += num and read the next. 4 + 7 + 2 = 13. The number of rounds is unknown in advance: while.
  6. Three nested decisions: score ≥ 85? → A; else score ≥ 70? → B; else score ≥ 50? → C; else F. Java: if … else if … else.

Summary

References

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

The End

Chapter 1.4: Flowcharts
Previous: Chapter 1.3: Algorithms · Next: Chapter 2.1: Programming
1 / 1 Sercan KÜLCÜ. All rights reserved.