Unit 1 · Basics of Computer Programming

1.3.1Conventions, and when to use pseudocode

Conventions used in this module

PurposeKeyword and form
Start and endBEGIN ... END
InputREAD name
OutputPRINT value
Assignmenttotal = total + i
SelectionIF condition THEN ... ELSE ... END IF
Pre-test loopWHILE condition DO ... END WHILE
Counted loopFOR i = 1 TO n DO ... END FOR
Post-test loopREPEAT ... UNTIL condition
ProcedurePROCEDURE name(parameters) ... END PROCEDURE

Indent the body of every structure. Use meaningful variable names. Some books write assignment as total ← total + i; this module uses =.

Operators you can use

KindOperatorsExample
Arithmetic+ - * /area = length * width
Whole-number division and remainderDIV, MOD17 DIV 5 is 3, 17 MOD 5 is 2
Comparison= != < <= > >=IF marks >= 50 THEN
LogicalAND OR NOTIF age >= 18 AND hasID THEN

MOD (the remainder) is very useful: n MOD 2 = 0 tests whether n is even, and n MOD d = 0 tests whether d divides n exactly.

The three loops compared

LoopWhen the condition is testedSmallest number of passesUse it when
FOR i = 1 TO nBefore each pass (it counts)0You know how many times to repeat
WHILE condition DOBefore each pass0You repeat while something is true and might not need to run at all
REPEAT ... UNTIL conditionAfter each pass1The body must run at least once, for example asking for a password

Note the different meaning of the condition: WHILE repeats while the condition is true; REPEAT ... UNTIL repeats until the condition becomes true.

Rules for good pseudocode

Flowchart or pseudocode?

Flowcharts show the overall flow visually and suit beginners and presentations. Pseudocode is faster to write, easier to edit and closer to real code. Professionals usually use pseudocode.

From pseudocode to Java

Because pseudocode is close to real code, each line translates almost directly:

PseudocodeJava
READ marksint marks = input.nextInt(); (with a Scanner called input)
PRINT totalSystem.out.println(total);
IF a > b THEN ... ELSE ... END IFif (a > b) { ... } else { ... }
WHILE x != 0 DO ... END WHILEwhile (x != 0) { ... }
FOR i = 1 TO n DO ... END FORfor (int i = 1; i <= n; i++) { ... }
REPEAT ... UNTIL donedo { ... } while (!done);
n MOD 2n % 2
a = b (comparison in a condition)a == b

Watch the last row: in pseudocode = is used both to assign and to compare, but Java uses = to assign and == to compare. Also note that REPEAT ... UNTIL becomes a do ... while loop with the condition reversed.

Remember

  • Pseudocode is for people, so clarity matters more than strict rules.
  • Indent and close every structure.
  • WHILE may run zero times; REPEAT ... UNTIL always runs at least once.