Pseudocode and flowcharts
On This Lesson 11 topics
Lesson Overview
You can now state a problem clearly and split it into plain-sentence steps. Plain sentences are a good start, but they are loose: they do not show clearly where a loop begins, which steps belong inside a decision, or what happens in each branch. Java would show all that, but Java comes with strict rules about syntax that distract you while you are still thinking.
This lesson teaches two tools that sit between plain sentences and Java: pseudocode and flowcharts. Both let you describe the logic with structure and no syntax rules, so you can find mistakes while they are still cheap to fix. Back to our map analogy: pseudocode is a written list of directions, and a flowchart is the road map drawn as a picture.
Why this matters: changing a line of pseudocode takes seconds, while changing a tangle of Java can take much longer. Sketches like these also explain a rule to someone who does not read code.
The previous lesson, "Decomposition", gave you the steps.
Learning Objectives
By the end of this lesson you will be able to:
- Write pseudocode that uses SET, IF, FOR, WHILE, and PRINT or RETURN with clear indentation.
- Draw a flowchart with start/end shapes, step boxes, decision diamonds, and arrows.
- Choose between pseudocode and a flowchart for a given problem.
- Convert pseudocode into Java and check that they match.
- Find a logic mistake in a plan before writing code.
Written Explanation
What pseudocode is
Pseudocode is plain language with code-like structure. It is not a real programming language, so no compiler reads it and there are no syntax errors. Its purpose is to make the logic visible: the order of the steps, the repeated parts, and the decisions.
A common vocabulary keeps it readable. These words are conventions, not rules, and many courses use slightly different ones:
| Word | Meaning | Example |
|---|---|---|
SET | Give a variable a value | SET total = 0 |
IF ... ELSE | Choose between actions | IF grade >= 50 |
FOR EACH | Repeat for every item | FOR EACH value IN values |
WHILE | Repeat as long as a condition holds | WHILE r * r < n |
PRINT / RETURN | Show or give back a result | RETURN largest |
Indentation is the one structural rule worth keeping: everything inside a loop or a decision is indented under it, so the reader can see where it starts and ends.
Good pseudocode and bad pseudocode
Good pseudocode is precise about logic and relaxed about syntax. Compare:
Too vague: Find the biggest one.
Good: SET largest = first value
FOR EACH other value
IF value > largest
SET largest = value
RETURN largest
Too much Java: for (int i = 1; i < a.length; i++) { if (a[i] > max) max = a[i]; }The vague version hides the loop and the comparison. The "too much Java" version spends attention on semicolons and brackets. The middle version names the variables, shows the loop, and shows the decision, but it has no braces and no types.
A good test: could a friend who has never seen your problem follow it and get the right answer by hand? If yes, the pseudocode is good enough.
What a flowchart is
A flowchart draws the same logic as shapes joined by arrows. The common conventions are:
| Shape | Used for |
|---|---|
| Rounded box or oval | Start and end |
| Rectangle | A step or an action |
| Diamond | A yes/no decision, with two arrows leaving it |
| Arrow | The order in which things happen |
A diamond holds a question that can be answered yes or no, such as value > largest?. Each of the two arrows leaving it is labelled. A loop shows up as an arrow that goes back to an earlier shape.
Since we cannot draw boxes here, the flowcharts in this lesson are written as text. Rectangles are [ ], diamonds are < >, and arrows are described by lines and labels:
[Start]
v
[SET largest = first value]
v
[SET i = 1]
v
<i < length?> --no--> [RETURN largest] --> [End]
| yes
v
<values[i] > largest?> --no--+
| yes |
v |
[SET largest = values[i]] |
v |
+-------------------------+
v
[SET i = i + 1] --> back to <i < length?>I have used the shape conventions that are widely taught; whether your course or tool draws them exactly this way can vary, so follow your instructor's version if it differs.
Which one to use?
Pseudocode suits loops, calculations, and logic with many steps; it is faster to write and closer to code. A flowchart suits decisions with several branches and explaining the logic to non-programmers, because it shows every path at a glance. For many problems pseudocode alone is enough.
Finding mistakes in the plan
The value of a plan is that you can check it cheaply. Ask three questions of any pseudocode:
- Does every variable have a value before it is used? (Did you SET
largestbefore comparing?) - Does every loop end? (Does something inside change the condition?)
- Does every decision cover all cases? (What happens in the ELSE?)
Then run your plan on the example from the first lesson. The next lesson turns this into a precise technique.
From pseudocode to Java, and keeping both
When the plan looks right, translate it line by line. SET becomes an assignment, FOR EACH becomes a for loop or an enhanced for, IF stays if. If you change your mind while coding, change the plan too, so the plan and the code always describe the same program. A plan that no longer matches the code is worse than no plan.
Examples
Example 1: the largest value (simple)
The pseudocode shown above translates directly:
public class Largest {
static int largest(int[] values) {
int largest = values[0];
for (int i = 1; i < values.length; i++) {
if (values[i] > largest) {
largest = values[i];
}
}
return largest;
}
public static void main(String[] args) {
System.out.println(largest(new int[]{4, 9, 7}));
}
}Real output: 9. Line by line: SET largest = first value is int largest = values[0];, FOR EACH other value is a loop starting at index 1 (index 0 is already in largest), and the IF and inner SET are the if block. The plan and code match step for step. Note what the plan assumes: the array has at least one value. The next lessons show how to handle the case where it does not.
Example 2: is a number a perfect square? (practical)
Problem: given an int n, say whether it is a perfect square, such as 16 (4 times 4). Restatement: input int n, output boolean. Decision: negative numbers are not perfect squares.
Pseudocode:
IF n < 0
RETURN false
SET r = 0
WHILE r * r < n
SET r = r + 1
RETURN (r * r == n)Flowchart as text:
[Start]
v
<n < 0?> --yes--> [RETURN false] --> [End]
| no
v
[SET r = 0]
v
<r * r < n?> --yes--> [SET r = r + 1] --> back to <r * r < n?>
| no
v
[RETURN r * r == n] --> [End]Both describe one loop: keep growing r until its square reaches n or goes past it. Then one comparison decides. Java:
static boolean isPerfectSquare(int n) {
if (n < 0) return false;
int r = 0;
while (r * r < n) {
r++;
}
return r * r == n;
}Called with 16, 15, 0, and -4, it printed true false true false. Checking by hand against the plan: 16 stops at r = 4 and 4 times 4 equals 16, so true. 15 stops at r = 4 as well (16 is not below 15) and 16 does not equal 15, so false. Zero never enters the loop and 0 equals 0, so true. A good plan answers the unusual questions (is zero a perfect square?) because the loop and the final comparison handle it without special cases. (Very large n can overflow int when r * r is computed; that is a limit we note and do not solve here.)
Example 3: leap years and the order of decisions (realistic)
Problem: decide whether a year is a leap year. The rule, as commonly stated, is: every year divisible by 4 is a leap year, except years divisible by 100, unless they are also divisible by 400. (This is the rule of the Gregorian calendar; I did not look up an official calendar source for this lesson, so check it if the exact rule matters to you.)
A first pseudocode might test 4 first, and goes wrong. Tracing 1900 shows why: it is divisible by 4, so a "check 4 first" plan says yes, but 1900 is not a leap year. Reordering from the most specific rule to the least specific fixes it:
IF year is divisible by 400
RETURN true
IF year is divisible by 100
RETURN false
RETURN (year is divisible by 4)In flowchart form this is a chain of two diamonds followed by a final rectangle, with each yes or no arrow leading to its answer. The shape makes the order of the tests visible, and moving a diamond changes the answer. Java:
static boolean isLeapYear(int year) {
if (year % 400 == 0) return true;
if (year % 100 == 0) return false;
return year % 4 == 0;
}Called with 2024, 1900, 2000, and 2023, it printed true false true false. This is a typical business-rule situation: the order of the checks is the logic, and the plan is where you get it right before coding.
Backend Insight
Backend developers use both tools in their daily work, usually informally. A sketch of a login flow with diamonds ("password correct?", "account locked?") helps the team agree on every path before anyone codes. A few lines of pseudocode in a ticket or a code comment explain a pricing rule to a reviewer who knows the business but not Java.
Plans also help when something breaks. If the plan says an expired coupon returns a message and the code returns an error, you know which one is the bug: the plan is the reference the code is checked against.
Common Mistakes
Mistake 1: Pseudocode that is secretly Java
- Incorrect:
for (int i = 0; i < n; i++) { ... }in your plan. - Correct:
FOR EACH value IN valuesorFOR i FROM 1 TO n.
You gain nothing by writing Java twice. Keep the plan about logic.
Mistake 2: Pseudocode that is too vague
- Incorrect: "Process the numbers and return the answer."
- Correct: Name the variables, show the loop, show the decision.
Mistake 3: Forgetting the "no" branch
Every diamond has two exits. If your flowchart has only the yes arrow, then the code will have an if with no plan for the other case.
Mistake 4: Wrong order of decisions
As the leap-year example showed, the order of tests can change the answer. Put the most specific test first.
Exercises
Try each exercise yourself before opening the solutions.
Level A: Foundation
A1. What is the difference between pseudocode and Java?
Show solution A1
A1. Pseudocode describes logic in plain language with code-like structure and has no syntax rules, so nothing checks it. Java must follow strict syntax and is checked by the compiler.
A2. Name the flowchart shape for a start, for a step, and for a yes/no decision.
Show solution A2
A2. Start and end: rounded box or oval. Step: rectangle. Decision: diamond.
A3. Rewrite this vague plan as pseudocode: "Add up the numbers and say what the total is."
Show solution A3
A3.
SET total = 0
FOR EACH number IN numbers
SET total = total + number
PRINT totalLevel B: Application
B1. Write pseudocode for "return the sum of the even numbers in an array".
Show solution B1
B1.
SET sum = 0
FOR EACH value IN values
IF value is even
SET sum = sum + value
RETURN sumB2. Write pseudocode for "count how many values in an array are greater than a given limit". Then draw the flowchart as text.
Show solution B2
B2.
SET count = 0
FOR EACH value IN values
IF value > limit
SET count = count + 1
RETURN count[Start] -> [SET count = 0] -> <more values?> --no--> [RETURN count] -> [End]
| yes
v
<value > limit?> --no--+
| yes |
v |
[SET count = count + 1]|
+--------------+--> back to <more values?>B3. This pseudocode for "is a number even?" has two problems. Find them.
IF n % 2 == 0
PRINT "even"
PRINT "odd"Show solution B3
B3. First, there is no ELSE, so "odd" is printed for every number, even for even ones: after printing "even" the plan continues to the last line. Second, the plan prints rather than returns, which is fine only if that was the requirement. Fix: IF n % 2 == 0 PRINT "even" ELSE PRINT "odd".
Level C: Challenge
C1. Write pseudocode for "add up the digits of a non-negative whole number" (for 305 the answer is 8). Decide what happens for 0. Then translate it to a Java method static int digitSum(int n), run it on 0, 7, 305, and 2024, and write your results. Hint: n % 10 is the last digit and n / 10 removes it.
Show solution C1
C1.
SET sum = 0
WHILE n > 0
SET sum = sum + (n mod 10)
SET n = n div 10
RETURN sumFor 0 the loop never runs and the answer is 0, which is correct. Java:
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}Running it on 0, 7, 305, and 2024 printed 0 7 8 8.
C2. A shop gives 20% off for orders of 100 or more, 10% off for orders of 50 or more, and nothing otherwise. Write pseudocode, and explain what goes wrong if you test "50 or more" first.
Show solution C2
C2.
IF total >= 100
SET rate = 20
ELSE IF total >= 50
SET rate = 10
ELSE
SET rate = 0
RETURN total * rate / 100If you test "50 or more" first, an order of 120 matches it, and gets 10% instead of 20%: the broader test hides the narrower one.
Mini Challenge
Choose "decide the letter grade for a mark: 80 and above is A, 65 and above is B, 50 and above is C, otherwise F".
- Write pseudocode.
- Draw a flowchart as text, with a diamond for each test.
- Run your plan on 80, 79, 65, and 49 by hand.
- Translate it to a Java method returning a
charand check that it matches your plan.
Check your work: every diamond has two exits, the tests go from the highest boundary down, and your hand results match the Java output.
Summary & Next Lesson
Key takeaways
- Pseudocode is plain language with code-like structure (SET, IF, FOR, WHILE). It has no syntax rules and no compiler.
- A flowchart uses rectangles for steps, diamonds for yes/no decisions, and arrows for order.
- Use pseudocode for loops and calculations; use a flowchart when the decisions and paths are the hard part.
- Check a plan for unset variables, loops that never end, and decisions with missing branches.
- Keep the plan and the code in agreement. Update both when either changes.
Next lesson
You can now write a plan. The next lesson, "Hand-tracing with a variable table", shows how to execute a plan or a program by hand, one step at a time, to see what it really does.
Self-check
- What shape is a decision in a flowchart?
- Why does pseudocode have no syntax errors?
- What does every diamond need?
- In the leap-year example, why did the order of the tests matter?
- Why keep the plan next to the code?
Show answers
- A diamond.
- Nothing compiles or checks it; its only purpose is to show the logic to a human reader.
- Two labelled exits: yes and no.
- Because 1900 is divisible by 4, a "check 4 first" plan returns true for it, but the 100 and 400 rules should have been tested first.
- So that both describe the same program, and the plan can be used as the reference when the code misbehaves.
References
- Oracle, The Java Tutorials: The while and do-while Statements. Supports how a
whileloop repeats while its condition is true, which the perfect-square example uses. - Oracle, The Java Tutorials: The for Statement. Supports the for-loop form used when translating
FORto Java. - Not verified: the flowchart shape conventions (rounded start/end, rectangle, diamond) are a widely taught convention that I did not check against a standard such as ISO 5807; the leap-year rule is as commonly stated and was not checked against an official calendar source. The Java examples and the C1 solution were compiled and run with JDK 21 (real output shown).
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.