Lesson 1.1 · Unit 1 · CED topic 1.1

Algorithms, programs, and compilers

An algorithm is a step-by-step process for finishing a task or solving a problem. You already follow algorithms all day: a recipe, the directions to a friend's house, the steps for long division. A program is an algorithm written in a language a computer will accept, and this course teaches that language: Java.

Two ideas make an algorithm precise. First, the steps are sequenced: they happen one at a time, in a defined order, and swapping two steps can change the result. Second, each step is exact enough that nobody has to guess what it means. "Add a little tip" is not a step a computer can follow; "multiply the bill by 0.15" is.

Required content · LO 1.1.A, LO 1.1.B, LO 1.1.C

Learning objectives.

  • 1.1.A. Represent patterns and algorithms found in everyday life using written language or diagrams.
  • 1.1.B. Explain the code compilation and execution process.
  • 1.1.C. Identify types of programming errors.

Essential knowledge.

  • 1.1.A.1. Algorithms define step-by-step processes to follow when completing a task or solving a problem. These algorithms can be represented using written language or diagrams.
  • 1.1.A.2. Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.
  • 1.1.B.1. Code can be written in any text editor; however, an integrated development environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile, and run code.
  • 1.1.B.2. A compiler checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.
  • 1.1.C.1. A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler.
  • 1.1.C.2. A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
  • 1.1.C.3. A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
  • 1.1.C.4. An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the program’s execution.

Describing an algorithm before you code it

You can describe an algorithm in written language or in a diagram, and the exam expects both. A diagram often shows the order at a glance; the same steps in plain sentences are easier to turn into code line by line.

Start Read the bill tip = bill × 0.15 total = bill + tip Display total step 1 step 2 step 3 step 4
Figure 1.1. An algorithm drawn as a flowchart. Each box is one step, and the arrows fix the order: the tip must be computed before the total can use it.

Here is the same algorithm in written form.

  1. Read the amount of the bill.
  2. Compute the tip as the bill times 0.15.
  3. Compute the total as the bill plus the tip.
  4. Display the total.

Try swapping steps 2 and 3. The total would be computed before the tip exists, so the algorithm no longer does what you meant. That is what sequencing means: an order is part of the definition of the algorithm.

From source code to a running program

Java code can be written in any text editor, but programmers use an integrated development environment (IDE) because it bundles the tools you need to write, compile, and run code in one place. The path a Java program takes is always the same.

Main.javasource code javacthe compiler Main.classbytecode javathe JVM Outputwhat you see Syntax error found: no .class file is made, so nothing runs Run-time error or exception: the program stops in mid-run 1. you write 2. it is checked 3. it is produced 4. it is run
Figure 1.2. The compiler can stop a program before it starts; only the JVM can stop it while it runs. A logic error passes through both stages unnoticed.
  1. You write source code in a file ending in .java.
  2. The compiler (javac) checks that code against the rules of the language. If it finds a mistake it reports it and stops; nothing can run until every error it can detect is fixed.
  3. If the code is acceptable, the compiler produces bytecode in a .class file.
  4. The Java Virtual Machine (the JVM, started with java) runs the bytecode.

Every program on the exam sits inside a class, and execution begins at the first statement of main:

public class Main {
    public static void main(String[] args) {
        // statements run in order, top to bottom
    }
}

The file is named after its class (Main.java). Statements end in semicolons and blocks are wrapped in braces. On the exam, snippets usually show only the statements; you can assume the class and main around them.

Four ways code goes wrong

The compiler can catch some mistakes and cannot catch others. The difference is the most tested idea in this lesson.

Kind of errorWhat is wrongWho finds itWhat you see
Syntax errorThe code breaks a rule of the language (missing semicolon, misspelled keyword, wrong type)The compilerAn error message with a line number; no .class file; the program never runs
Logic errorThe algorithm is wrong, so the program runs and gives the wrong answerYou, by testing with data whose answer you already knowOutput that is wrong but looks normal
Run-time errorThe program breaks while it is runningThe JVM, during the runThe program stops abnormally, often after printing some output
ExceptionA kind of run-time error that the compiler could not foresee; it interrupts the normal flow of the programThe JVMA named exception such as ArithmeticException and a message

The rows are not equal in how loudly they announce themselves. A syntax error shouts at compile time. An exception shouts at run time. A logic error says nothing at all, which is why testing matters: the only way to find it is to compare what the program did with what it should have done.

Worked example · a program that runs

Convert 21.5 degrees Celsius to Fahrenheit and print the result.

public class Main {
    public static void main(String[] args) {
        double celsius = 21.5;
        double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
        System.out.println(celsius + " C is " + fahrenheit + " F");
    }
}

Compiled and run, it prints:

21.5 C is 70.7 F

Every statement executed once, top to bottom. The sequence matters: fahrenheit could not be computed before celsius had a value.

Worked example · the same program, one semicolon short

Delete the semicolon after 21.5 and compile again. The compiler stops and reports where it got lost.

public class Main {
    public static void main(String[] args) {
        double celsius = 21.5
        System.out.println(celsius);
    }
}
Main.java:3: error: ';' expected
        double celsius = 21.5
                             ^
1 error

No .class file is produced, so nothing runs and nothing prints. The caret sits just after the last good token, so the problem is at the end of the line named, not the start of the next one. This is a syntax error.

Worked example · one program, two different errors

The compiler accepts the code below, so the problem cannot be a syntax error. It fails later.

int total = 120;
int count = 0;
System.out.println("Average: " + total / count);
Exception in thread "main" java.lang.ArithmeticException: / by zero

Integer division by zero cannot be checked in advance when the divisor is a variable, so the compiler lets it through and the JVM stops the run. This is a run-time error, specifically an exception.

Now a program that compiles, runs to the end, and is still wrong. The goal is the average of 4 and 10, which is 7.

int a = 4;
int b = 10;
System.out.println("Average: " + (a + b / 2));
Average: 9

The multiplication-and-division-first rule made b / 2 happen before the addition, so the algorithm computed 4 + 5. Nothing crashed and nothing was reported. Only a test whose answer you already knew (7) revealed it. This is a logic error.

Exam focus

Exam questions in this topic ask you to identify the kind of error from a description or a code segment, and to put algorithm steps in a correct order. Use who and when to decide: complaints before the program starts come from the compiler (syntax); complaints in the middle of a run come from the JVM (run-time or exception); wrong answers with no complaint are logic errors. On the free-response section, your code is read for whether it would compile, so unbalanced braces and missing semicolons matter even though a human grades it.

Practice
  1. Which of the following is a syntax error?
    A.  int total = 10 / zero;   // zero holds 0
    B.  int sum = a + b / 2;     // meant (a + b) / 2
    C.  System.out.println("Done")
    D.  int count = 5;
    Show answer

    C. The statement is missing its closing semicolon, which breaks a rule of the language, so the compiler reports it before the program can run. A is a run-time error (an ArithmeticException when the division happens), B is a logic error (it compiles and runs but computes the wrong value), and D is correct code.

  2. A program compiles without any message and prints Total: 40 for three items that cost 10, 20, and 30. What kind of error is this, and how would you find it?
    Show answer

    A logic error. The program ran to the end, so the compiler and the JVM had no complaint. You find it by testing with data whose answer you know: the three prices sum to 60, so 40 shows the algorithm is wrong.

  3. Put these steps in an order that computes the area of a circle with radius 3.
    1. Display area
    2. Set area to 3.14 * radius * radius
    3. Set radius to 3
    Show answer

    3, 2, 1. The radius must have a value before the area uses it, and the area must exist before it is displayed. The order is part of the algorithm.

  4. The following is run. Name the kind of error and say whether any output appears.
    int items = 0;
    int people = 5;
    System.out.println("Sharing...");
    System.out.println(people / items);
    Show answer

    A run-time error, an ArithmeticException. The compiler accepts the code, so the first line prints Sharing..., and then the JVM stops the program at the division. Output appears before the failure.

  5. Why do most programmers write Java in an IDE rather than a plain text editor?
    Show answer

    An IDE combines the tools for writing, compiling, and running code in one place, so a programmer can fix compiler errors and test the program without leaving the editor. A text editor can produce the same code, but it provides none of those tools.

  6. True or false: the compiler detects every error in a program before it runs.
    Show answer

    False. The compiler detects errors in the rules of the language (syntax errors, and mismatches it can see). It cannot detect logic errors, and it cannot detect run-time errors such as dividing by a variable that holds zero, so those appear only when the program is tested or run.

1.2 Variables and data types →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course