Introduction to Algorithms, Programming, and Compilers
Big idea: A program is an algorithm written in a language the computer can run. Before it runs, the compiler checks it, and the bugs that slip past fall into three kinds.
- Represent patterns and algorithms found in everyday life using written language or diagrams.
- Explain the code compilation and execution process.
- Identify types of programming errors.
Algorithms and sequencing
An algorithm is a step-by-step process for completing a task, like a recipe or the directions to school. You can write one in plain language or draw it as a flowchart before you write any code.
Sequencing means the steps run one at a time, in order. Java runs the statements in main from top to bottom unless something (an if, a loop, a method call) changes the flow.
System.out.println("Preheat the oven");
System.out.println("Mix the batter");
System.out.println("Bake 30 minutes");OutputPreheat the oven Mix the batter Bake 30 minutes
From source code to a running program
You write source code in a text editor or an IDE (an editor that can also compile and run code). The compiler checks the code and translates it into a form the computer can run. If the compiler finds errors, nothing runs until you fix them.
- Write the code (
.javafile). - Compile: the compiler reports syntax errors or produces runnable code.
- Run: the program executes. Run-time errors and logic errors show up here.
Three kinds of errors
An exception is a run-time error the compiler did not detect. It interrupts the normal flow of the program. Logic errors are the hardest to find: the only way is to test the program with data whose correct answer you already know.
| Error | When it shows up | Example |
|---|---|---|
| Syntax (compile-time) | The compiler refuses to compile | Missing semicolon, misspelled keyword, unmatched brace |
| Run-time | While running; the program usually stops | Dividing an int by zero, an index out of bounds |
| Logic | Runs fine but gives the wrong answer | Using > instead of >=, averaging with the wrong count |
- An algorithm is a step-by-step process. Sequencing runs steps one at a time, in order.
- The compiler catches some errors (syntax errors). They must be fixed before the program can run.
- A logic error produces wrong results. Testing with known data finds it.
- A run-time error happens during execution. An exception is a run-time error that interrupts execution.
- Code that compiles can still be wrong. Compiling only proves the syntax is valid.
- An exception is a run-time error, not a compile-time error.
- When a question says the code "compiles and runs but produces the wrong result," the answer is a logic error.