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.
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.
Here is the same algorithm in written form.
- Read the amount of the bill.
- Compute the tip as the bill times 0.15.
- Compute the total as the bill plus the tip.
- 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.
- You write source code in a file ending in
.java. - 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. - If the code is acceptable, the compiler produces bytecode in a
.classfile. - 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 error | What is wrong | Who finds it | What you see |
|---|---|---|---|
| Syntax error | The code breaks a rule of the language (missing semicolon, misspelled keyword, wrong type) | The compiler | An error message with a line number; no .class file; the program never runs |
| Logic error | The algorithm is wrong, so the program runs and gives the wrong answer | You, by testing with data whose answer you already know | Output that is wrong but looks normal |
| Run-time error | The program breaks while it is running | The JVM, during the run | The program stops abnormally, often after printing some output |
| Exception | A kind of run-time error that the compiler could not foresee; it interrupts the normal flow of the program | The JVM | A 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.
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.
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.
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 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.
- 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
ArithmeticExceptionwhen the division happens), B is a logic error (it compiles and runs but computes the wrong value), and D is correct code. - A program compiles without any message and prints
Total: 40for 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.
- 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.
- 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 printsSharing..., and then the JVM stops the program at the division. Output appears before the failure. - 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.
- 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.