kids encyclopedia robot

Logic error facts for kids

Kids Encyclopedia Facts

A logic error is a common type of mistake, or bug, in a computer program. It causes the program to do something unexpected or give a wrong answer. Imagine you're writing instructions for a robot. If you tell it to "turn left, then walk 5 steps, then turn right," but you meant "turn right, then walk 5 steps, then turn left," that's a logic error! The robot follows your instructions exactly, but the result isn't what you wanted.

The tricky part about logic errors is that the program's syntax is usually correct. This means the computer doesn't see it as a "grammar" mistake and won't show an error message. Because of this, logic errors can be very hard to find and fix.

What is a Logic Error?

A logic error happens when a program runs without crashing, but it doesn't do what it's supposed to do. It might calculate something incorrectly, show the wrong information, or behave strangely. The computer follows the instructions you gave it, but those instructions don't lead to the correct outcome.

Why are Logic Errors Hard to Find?

Unlike other types of errors, a logic error doesn't usually stop the program from running. The program might seem to work fine, but the results are wrong. This is like a calculator that adds 2 + 2 and gives you 5. It still calculates, but the answer is incorrect. Programmers often have to test their programs very carefully with different inputs to spot these hidden mistakes.

Example of a Logic Error

Let's look at a simple example from the C programming language. This code is meant to find the average of two numbers.

int average(int a, int b)
{
    return a + b / 2;     /* should be (a + b) / 2 */
}

In this example, the programmer wanted to add `a` and `b` together, and then divide the total by 2. However, because of the way math works in programming (and in regular math!), division happens before addition. So, `b / 2` is calculated first, and then `a` is added to that result.

For example, if `a` is 10 and `b` is 4:

  • The code calculates `10 + (4 / 2)`, which is `10 + 2 = 12`.
  • The correct average should be `(10 + 4) / 2`, which is `14 / 2 = 7`.

The program runs perfectly fine, but it gives the wrong answer! To fix this, the programmer needs to add parentheses to make sure the addition happens first: `(a + b) / 2`.

kids search engine
Logic error Facts for Kids. Kiddle Encyclopedia.