Program Errors, Testing and Debugging: Syntax, Logic and Runtime Errors

Almost no program works perfectly the first time – not even for professional programmers! In this post you will learn the three types of program errors, how to choose good test data, and some techniques for debugging (finding and fixing errors).

Build on what you learned in Forms 1–3

These Lower School ICT posts cover the basics of this topic:

In this post:

  • Syntax errors
  • Logic errors
  • Runtime errors
  • Test data: normal, boundary and erroneous
  • Debugging techniques
The famous “first computer bug”: a moth found trapped in the Harvard Mark II computer in 1947 and taped into the log book. Finding and fixing errors is still called debugging.
The famous “first computer bug”: a moth found trapped in the Harvard Mark II computer in 1947 and taped into the log book. Finding and fixing errors is still called debugging.

Image source: File:H96566k.jpg

Syntax errors

A syntax error happens when the rules (grammar) of the programming language are broken – for example a missing bracket, a missing semicolon or a misspelt keyword like pritn. The translator finds these errors, and the program will not run until they are fixed.

Python

print("Hello, Trinidad!"    # missing closing bracket

C

#include <stdio.h>

int main(void)
{
    printf("Hello, Trinidad!\n")    /* missing semicolon */
    return 0;
}

Python reports SyntaxError: '(' was never closed. The C compiler (gcc) reports error: expected ';' before 'return'.

Logic errors

A logic error is a mistake in the design of the program. The program runs, but gives the wrong result. The computer cannot spot it for you – you find it by testing and comparing with the expected answer (a trace table helps!).

Python

# Logic error: the brackets are missing, so only score3 is divided by 3
score1 = 60
score2 = 70
score3 = 80
average = score1 + score2 + score3 / 3     # WRONG - gives 156.67
print("Average:", average)
average = (score1 + score2 + score3) / 3   # CORRECT - gives 70.0
print("Average:", average)

C

/* Logic error: the brackets are missing, so only score3 is divided by 3 */
#include <stdio.h>

int main(void)
{
    float score1 = 60, score2 = 70, score3 = 80, average;

    average = score1 + score2 + score3 / 3;     /* WRONG - gives 156.67 */
    printf("Average: %.2f\n", average);
    average = (score1 + score2 + score3) / 3;   /* CORRECT - gives 70.00 */
    printf("Average: %.2f\n", average);
    return 0;
}

Both programs print 156.67 for the wrong line and 70 for the correct line. Other common logic errors: using > instead of >=, or a loop that runs one time too many.

Runtime errors

A runtime error happens while the program is running and usually makes it crash. Examples: dividing by zero, trying to open a file that does not exist, or a user typing letters when a number was expected.

Python program with a runtime error

# Runtime error: dividing by zero crashes the program while it runs
total_marks = int(input("Total marks: "))
num_students = int(input("Number of students: "))
print("Class average:", total_marks / num_students)

If the user enters 0 students, Python stops with ZeroDivisionError: division by zero. A good programmer checks the input first:

Python

# Fixed: check the value before dividing
total_marks = int(input("Total marks: "))
num_students = int(input("Number of students: "))
if num_students > 0:
    print("Class average:", total_marks / num_students)
else:
    print("Number of students must be more than 0")

C

/* Fixed: check the value before dividing */
#include <stdio.h>

int main(void)
{
    int total_marks, num_students;

    printf("Total marks: ");
    scanf("%d", &total_marks);
    printf("Number of students: ");
    scanf("%d", &num_students);
    if (num_students > 0)
        printf("Class average: %.2f\n", (float) total_marks / num_students);
    else
        printf("Number of students must be more than 0\n");
    return 0;
}

Sample run with 300 and 0: Number of students must be more than 0.

Test data

Type of test dataMeaningExample for marks 0–100 with pass mark 50
NormalTypical, valid values the program should accept35, 72, 88
Boundary (extreme)Values at the edges of the valid range0, 49, 50, 100
Erroneous (abnormal)Invalid values the program should reject−5, 150, “abc”

Debugging techniques

  • Read the error messages – they usually give the line number.
  • Dry run with a trace table – follow the code by hand to see where values go wrong.
  • Print statements – temporarily display the values of variables at different points.
  • Use a debugger – step through the program line by line and watch the variables (IDEs such as Thonny or Code::Blocks have this).
  • Test small parts one at a time.

Try it: Error-type sorter

Decide whether each problem is a syntax, logic or runtime error.

The keyword print is typed as prnt
The program uses > 50 instead of >= 50, so a mark of 50 shows “Fail”
The program crashes when the user enters 0 as the number to divide by
A closing bracket is missing at the end of a line
The total is calculated as price + quantity instead of price * quantity
The program crashes because a file it must open has been deleted

Related

Related: How to Approach a Dry run using test data and trace tables to uncover errors in your algorithm

Paper 1 practice (multiple choice)

Choose the best answer for each question. Try them all before you check.

1. A missing semicolon in a C program is an example of a
(A) logic error
(B) syntax error
(C) runtime error
(D) linking error

2. A program runs but displays the wrong total. This is MOST likely a
(A) syntax error
(B) logic error
(C) runtime error
(D) compiler error

3. Dividing a number by zero while a program is running causes a
(A) syntax error
(B) logic error
(C) runtime error
(D) typing error

4. For a program that accepts ages 13 to 19, which is BOUNDARY test data?
(A) 15
(B) 13
(C) 25
(D) −2

5. The process of finding and correcting errors in a program is called
(A) compiling
(B) linking
(C) debugging
(D) documenting

Show answers

1. B
2. B
3. C
4. B
5. C

Paper 2 practice (structured question)

A program is written to accept a student’s mark from 0 to 100 and display “Pass” for marks of 50 and over.

(a) Distinguish between a syntax error and a logic error. (2 marks)

(b) Give ONE example of:

(i) a runtime error (1 mark)

(ii) a logic error that could occur in this program (1 mark)

(c) Suggest ONE value of EACH type of test data for this program:

(i) normal (1 mark)

(ii) boundary (1 mark)

(iii) erroneous (1 mark)

(d) Describe TWO debugging techniques a programmer could use. (2 marks)

Total: 9 marks

Show answers

(a) A syntax error breaks the rules of the programming language and is found by the translator (1 mark); a logic error lets the program run but gives incorrect results (1 mark).

(b)

(i) The program crashes when the user types letters instead of a number (1 mark)

(ii) Using > 50 instead of >= 50 so a mark of 50 shows “Fail” (1 mark)

(c)

(i) A typical valid mark such as 72 (1 mark)

(ii) 0, 49, 50 or 100 (1 mark)

(iii) Any value below 0 or above 100, e.g. 150 (1 mark)

(d) Any two (1 mark each):
• dry run with a trace table
• adding print statements to display variable values
• using a debugger to step through the code
• reading error messages and line numbers
• testing small parts separately

Next: Declaring Variables and Translating Algorithms into Python and C

Syllabus link: This post is relevant to the CSEC® Information Technology Syllabus (CXC 30/G/SYLL 17), Section 8: Program Implementation, Specific Objective 3 (“perform checks and tests on programs to verify correctness”).

Attributions to media used in this post:

  • H96566k.jpg – Courtesy of the Naval Surface Warfare Center, Dahlgren, VA., 1988. – Public domain (via Wikimedia Commons)

Updates

2026/10/16

– Syntax highlighting added to code examples.

© 2026 Vedesh Kungebeharry. All rights reserved.

Testing Algorithms with Trace Tables (Desk Checks and Dry Runs)

How do you know your algorithm works before you type it into a computer? You do a desk check (also called a dry run): you pretend to be the computer and follow each step with pencil and paper, using a trace table to record the values.

Build on what you learned in Forms 1–3

These Lower School ICT posts cover the basics of this topic:

In this post:

  • What is a desk check / dry run?
  • How to build a trace table
  • Worked example with a loop
  • Using a trace table to find an error
  • Choosing test data

Desk checks and trace tables

A trace table has a column for each variable (identifier) and, if needed, a column for the output. You fill in one row for each pass (each time the loop runs or a value changes). At the end, compare the output with what you expected – if they match, the algorithm is correct for that test data.

Steps to complete a trace table

  1. Draw a column for each variable, plus Output.
  2. Go through the algorithm one line at a time.
  3. Every time a variable is given a new value, write it in its column (on a new row for each pass of a loop).
  4. When something is printed, write it in the Output column.
  5. Keep going until the algorithm ends.

Worked example

Pseudocode

1  total ← 0
2  count ← 1
3  WHILE count <= 4 DO
4      total ← total + count * 2
5      count ← count + 1
6  ENDWHILE
7  PRINT total
PasscounttotalOutput
Start10
122
236
3412
4520
End (count <= 4 is FALSE)52020

Notice that total goes 0 → 2 → 6 → 12 → 20, because each time we add count × 2 (2, 4, 6, 8). When count becomes 5, the condition count <= 4 is FALSE, so the loop stops and 20 is printed.

Using a trace table to find an error

Kerry-Ann wants to find the average of 3 numbers but her algorithm says average ← num1 + num2 + num3 / 3. Trace it with 60, 70 and 80:

num1num2num3averageExpected
607080156.6770

The trace table shows the answer is wrong. Only num3 was divided by 3! The fix is average ← (num1 + num2 + num3) / 3. This is a logic error – more on that in Section 8.

Choosing test data

Test with normal data (typical values), boundary data (values right at the edge, e.g. a mark of exactly 50 when the pass mark is 50) and erroneous data (values that should be rejected, like a mark of −5).

Try it: Trace table filler

Complete the trace table for this algorithm. Each row shows the values at the end of that pass.

x ← 3
y ← 1
FOR i ← 1 TO 3 DO
    y ← y * x
    x ← x − 1
ENDFOR
PRINT y
iyx
(start)13
1
2
3

What is printed at the end? (Answer: 6.)

Related

Related class recordings:
• How to Approach a Dry run using test data and trace tables to uncover errors in your algorithm
• Trace Table Exercise – Form 5 Opt D – 2025-10-08_08-55-28
• Reinforcement of Control Structures, Trace table test – Live class 5 OptD (2026-10-07_09-56-46)

Paper 1 practice (multiple choice)

Choose the best answer for each question. Try them all before you check.

1. A trace table is used to
(A) translate a program
(B) test an algorithm by recording the values of variables
(C) draw a flowchart
(D) store a program

2. In a trace table, the column headings are usually
(A) the line numbers only
(B) the variable names (identifiers)
(C) the flowchart symbols
(D) the programmer’s name

3. Working through an algorithm by hand to check it is called a
(A) compile
(B) dry run
(C) syntax check
(D) link

4. Given x ← 5, then x ← x + 3, then x ← x * 2, the final value of x is
(A) 10
(B) 16
(C) 13
(D) 8

5. Testing a pass-mark program with a mark of exactly 50 uses
(A) erroneous data
(B) boundary (extreme) data
(C) random data
(D) no data

Show answers

1. B
2. B
3. B
4. B
5. B

Paper 2 practice (structured question)

Study the following algorithm:

sum ← 0
FOR n ← 1 TO 4 DO
    READ value
    sum ← sum + value
ENDFOR
average ← sum / 4
PRINT sum, average

(a) Explain what is meant by a “dry run”. (2 marks)

(b) Copy and complete a trace table for the algorithm using the data 6, 3, 9, 2. (4 marks)

(c) State the output of the algorithm for this data:

(i) the sum (1 mark)

(ii) the average (1 mark)

(d) Identify the type of loop used in the algorithm. (1 mark)

Total: 9 marks

Show answers

(a) Working through the algorithm by hand, step by step (1 mark), recording the values of variables to check that the results are correct (1 mark).

(b)
• n = 1, value = 6, sum = 6 (1 mark)
• n = 2, value = 3, sum = 9 (1 mark)
• n = 3, value = 9, sum = 18 (1 mark)
• n = 4, value = 2, sum = 20 and average = 5 (1 mark)

(c)

(i) 20 (1 mark)

(ii) 5 (1 mark)

(d) FOR loop / counter-controlled loop (1 mark).

Next: Low-Level vs High-Level Languages and the Steps in Implementing a Program

Syllabus link: This post is relevant to the CSEC® Information Technology Syllabus (CXC 30/G/SYLL 17), Section 7: Problem-Solving and Program Design, Specific Objective 7 (“test algorithms for correctness”).

Attributions to media used in this post:

No third-party images are used in this post. Embedded videos are credited on YouTube to their channels.

© 2026 Vedesh Kungebeharry. All rights reserved.

Debugging in Code::Blocks: Breakpoints, Step Over, Step Into, Watches

In the previous lesson you found the copy-paste bug by spotting -9999 in the output. That worked because the program was tiny. In real programs you need a way to stop the program part-way through and look inside it. That tool is the debugger, and Code::Blocks has one built in. In this lesson you use it to watch the copy-paste bug happen, one line at a time.

In this lesson you will

  • Set a breakpoint and start a program in Debug mode
  • Step through code with Next line and Step into, and jump ahead with Continue
  • Inspect variables in the Watches window
  • Discover that a float cannot store 15.1 exactly

Try it: set up the buggy program

Open 002-UserInputCProgram and put the copy-paste bug back in, so that the second scanf reads into &x:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = -9999;
    float y = -9999;

    printf("Please enter a value for x:\n");
    scanf("%f", &x);
    printf("Please enter a value for y:\n");
    scanf("%f", &x);

    float sum = x + y;
    printf("The sum of %.2f and %.2f is %.2f\n", x, y, sum);
    return 0;
}

Check that the build target in the toolbar is set to Debug (not Release). The Debug target builds your program with extra information (GCC’s -g option) that lets the debugger match the running program to your lines of code.

Try it: breakpoints

A breakpoint is a marker that says “pause here”. Click in the margin just to the right of the line number beside the first scanf (line 10). A red dot appears. (You can also put the cursor on the line and press F5 to toggle a breakpoint.) Add a second breakpoint on the line float sum = x + y;.

Break it on purpose: breakpoints that are never hit

With both breakpoints set, click the usual Build and run button. Observe: the program runs from start to finish as if the breakpoints were not there.

Breakpoints only work when the program runs under the debugger. Stop the program. Then choose Debug → Start / Continue (F8, or the red arrow on the debugger toolbar).

This time the program starts, prints the first prompt, and stops. A yellow arrow appears in the margin at your first breaThe yellow arrow marks the line that will run next. It has not run yet. That is why nothing has been typed into the console so far.

Try it: step and watch

Open Debug → Debugging windows → Watches. It lists the local variables and their current values. Right now x and y both show -9999.

  1. Choose Debug → Next line (F7). The scanf runs and waits for you, so switch to the console, type 15.1 and press Enter. The yellow arrow moves down one line.
  2. Look at the Watches window. x now shows something like 15.1000004. Keep that in mind for later.
  3. Choose Debug → Start / Continue again. The program runs until it reaches the next breakpoint. On the way it asks for y: type 300.
  4. Look at the Watches window again. x has changed to 300, but y is still -9999. You have just watched the bug happen: the value meant for y went into x.
  5. Choose Debug → Stop debugger, fix the second scanf to use &y, and debug once more to confirm that both values arrive where they should.

What just happened

The debugger gives you three ways to move forward:

  • Next line (often called step over) runs the current line completely, then pauses on the next one. If the line calls a function, the whole function runs in one go.
  • Step into (Shift+F7) also runs one line, but if that line calls a function you wrote, it goes inside the function and pauses on its first line. This becomes useful in the next lesson, when you write your own functions. Library functions such as printf have no source code for the debugger to show, so stepping into them usually behaves like Next line.
  • Continue runs at full speed until the next breakpoint, or until the program ends.

One more surprise: when the program finishes under the debugger, the console window closes straight away, before you can read the output. A simple fix is to put a breakpoint on the return 0; line. The program then pauses there, with all of its output still on screen.

Name it: floats are not exact

Why did the Watches window show 15.1000004 instead of 15.1? A float stores numbers in binary, and most decimal fractions, including 0.1, cannot be written exactly in binary. In the same way, 1/3 cannot be written exactly in decimal (0.3333…). The computer stores the nearest value it can. You can see the stored value by asking printf for more decimal places than usual:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float x = 15.1;
    printf("%.2f\n", x);
    printf("%.10f\n", x);
    return 0;
}
15.10
15.1000003815

For everyday output, %.2f hides the tiny difference. Just remember never to expect a float to be exactly equal to a decimal value like 15.1. This matters later, when you start comparing values.

Key terms

  • Debugger: a tool that runs your program under control, so you can pause it and inspect it. Code::Blocks uses GDB.
  • Breakpoint: a marker on a line where the program pauses when run in Debug mode.
  • Next line (step over): run the current line, including any function it calls, and pause on the next line.
  • Step into: if the current line calls one of your functions, pause inside that function.
  • Continue: run until the next breakpoint.
  • Watches: a window showing the current values of variables.
  • Debug target: a build configuration that includes debugging information (-g).

Quick check

  1. You set a breakpoint, click Build and run, and the program never pauses. Why?

    Show answer

    Breakpoints only work under the debugger. Start the program with Debug → Start / Continue.

  2. The yellow arrow points at y = 6;. Has y been set to 6 yet?

    Show answer

    No. The arrow marks the line that will run next. Choose Next line, and then y becomes 6.

  3. What is the difference between Next line and Step into on a line that calls one of your own functions?

    Show answer

    Next line runs the whole function and stops on the following line. Step into goes inside the function and stops on its first line.

  4. Why might the Watches window show 2.0999999 for a float set to 2.1?

    Show answer

    Most decimal fractions cannot be stored exactly in binary, so the float holds the closest value it can.

Optional: a recorded demonstration of these steps starts around 2:10. Next line and Step into are demonstrated from about 18:00.

Part of the Introduction to C series. Next: Your First Function: void, Declarations, and Definitions

Debugging in Context with Flowgorithm

When developing a solution to a problem in program code, we usually aim to write a bit of code that implements part of the solution and run it to see if works.

Bugs can start here, they manifest as errors that prevent your code from being compiled or executed out right, or produce incorrect results.

It’s important to note in our context that programs written in source code must be translated to machine code , which is directly executable by your computer’s CPU.

The translation can take place

  • with the entire file, that is, the entire source code compiled into executable code or
  • line by line, i.e a single line of source code is interpreted as machine code, then executed and so on.

Syntax , Logical and Runtime Errors

The errors or bugs experienced while we develop our code can be classified into three types:

  • Syntax – this is were the rules for structuring the code are broken, or not followed which prevents the translation process – this applies to both the compiler and interpreter which performs these tasks. The result of a syntax error is that the entire program cannot be executed. The programmer must fix the errors and try running the program again.
  • Logical – this is where the translation process completes successfully, but when the program is run it produces incorrect results or undesired behavior. After producing the logical error, the program continues to run indefinitely or until it stops by reaching the end of code produced by the programmer.

    For example, let’s say we were developing a solution that would prompt the user to enter 2 numbers, and output the sum, the following are some logical errors:
    • if the user entered 5.1 and 5, and the program outputs 10, this is an incorrect result
    • if the user entered 5.1 and 5, and the program doesn’t output anything – this is incorrect behavior
    • if the user entered 5.1 and 5, and the program continues to prompt the user to enter another and another indefinitely.
  • Runtime – this is where the program halts abruptly during execution and stops running (sometimes called a crash). It definitely passed the translation process, and can be run successfully in most cases (with or without logical errors), however some cases of user input or abnormal conditions of the computer system , the program crashes. Some reasons include:
    • the program attempts to divide by 0,
    • the program tries to access a memory location that it is not allowed to by the operating system
    • the operating system runs out of resources to provide to the program.

Video

Teacher Demonstration In class: bugs in Flowgorithm

© 2023  Vedesh Kungebeharry. All rights reserved. 

Adding 2 numbers – (Declaring integer variables, Watching Variables)

0002-ADDING 2 integers , 5 and 6 no output

Exercise 1 

  1. Write code which declares 2 integer variables A and B .  Initialize A to 5 and B to 6.  Use a third variable , C to store the result of A+B.  

  2. Verify addition has occurred by using the variable watch window.

Demonstration Video

https://youtu.be/nfGwWUIZDaY

Download the files here: https://drive.google.com/file/d/15PfdndUqvnd_fLYPzctsgZMG4I9oSYtx/view?usp=sharing

Code

#include <stdio.h>
#include <stdlib.h>
int main()
{
   //declare and identify variables
   int a,b;
   int c;
   //Initialize the variables
   a=5;
   b=6;
   //Perform processing c <-- a+b
   c=a+b;
}

© 2021  Vedesh Kungebeharry. All rights reserved.