Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Introduction to Algorithms, Programming, and Compilers

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, programming is about writing step-by-step instructions (algorithms) for a computer, and a compiler helps translate your code and find certain types of errors before the program runs.

Why this matters

Imagine you're trying to explain to your friend, Carlos, how to make your famous game-day chili. You wouldn't just say "make chili." You'd give him a precise, step-by-step recipe: "First, brown one pound of ground beef in a large pot. Second, drain the fat. Third, add one can of kidney beans..." The order of these steps matters, right? You can't drain the fat before you've cooked the beef.

This recipe is an algorithm. It's a sequence of instructions to accomplish a task. In computer science, we write algorithms not for friends, but for computers. But what happens if you write a typo in your recipe, or if a step is just plain wrong? That's where we get into the world of programming errors and the tools that help us find them. Today, we'll break down how we give computers instructions and what happens when those instructions go wrong.

A recipe as an algorithm: precise, ordered steps.

Concept overview

flowchart TD
    A[Start: Write Java Code in IDE] --> B{Compile Code};
    B --> C{Syntax Error?};
    C -- Yes --> D[Fix Error in Code];
    D --> B;
    C -- No --> E[Bytecode Created];
    E --> F{Run Program};
    F --> G{Run-time Error?};
    G -- Yes --> H[Program Crashes];
    G -- No --> I{Check Output};
    I --> J[Correct Output];
    I --> K[Incorrect Output: Logic Error];
This diagram shows a flowchart of the programming process. It starts with writing code, which is then compiled. If there's a syntax error, the programmer must fix it; if not, the code is translated and can be run, which may result in a crash, a correct output, or an incorrect output due to a logic error.

Core explanation

Welcome to your first step in AP Computer Science A! It's going to be a great journey. Let's start with the absolute foundation of everything we'll do this year.

What is an Algorithm?

You use algorithms all the time, even if you don't use that word. An algorithm is just a finite, step-by-step set of instructions for solving a problem or completing a task.

Think about your morning routine:

  1. Wake up to alarm.
  2. Get out of bed.
  3. Brush teeth.
  4. Get dressed.
  5. Eat breakfast.
  6. Grab backpack and leave for school.

This is a perfect example of an algorithm. Notice two crucial things:

Your morning routine as a simple algorithm flow.
  • Steps
    It's broken down into individual, manageable actions.
  • Sequence
    The order is critical. You wouldn't leave for school before you wake up. This ordered nature of steps is called sequencing, and it's a core concept in programming. Every step is completed one at a time, in the order you specify.

We can represent algorithms with written language (like the list above) or with diagrams like flowcharts. The key is that the instructions must be clear and unambiguous. "Get ready for school" is a goal; the list above is an algorithm to achieve it.

From Algorithm to Running Program

So how do we give our algorithm to a computer? We write a program using a programming language, like Java.

You can write code in a simple text editor, like Notepad on Windows or TextEdit on a Mac. However, most programmers use an Integrated Development Environment (IDE). Think of an IDE like a professional chef's kitchen. You could cook a meal with a single pot and a campfire, but a chef's kitchen gives you a stove, oven, sharp knives, mixing bowls, and a clean workspace all in one place. An IDE (like Eclipse, IntelliJ, or VS Code) bundles a text editor with tools that help you write, test, and run your code more efficiently.

IDE vs. Text Editor: A professional kitchen vs. a campfire.

Now, here's a critical point: you write code in Java, but your computer's processor doesn't understand Java. It understands a much lower-level language called machine code. We need a translator.

This is where the compiler comes in.

The compiler is a special program that does two things:

  1. It checks your code for syntax errors.
  2. It translates your human-readable Java code into machine-readable bytecode. (For Java, it's a bit more nuanced than direct machine code, but we'll get to that later. For now, think of it as a translation step.)

Imagine you're writing an essay for English class. Before you turn it in, you use a grammar checker. The grammar checker finds typos, incorrect punctuation, and sentences that don't make sense. This is what the compiler does for your code. It enforces the strict grammar rules of the Java language.

This is where many students get stuck: You cannot run a program that has syntax errors. The compiler acts as a gatekeeper. If it finds a single mistake in your code's structure, it will stop, report the error, and refuse to create the executable program. You must fix all compiler-reported errors before your program can even attempt to run.

The Three Types of Errors

Even with the compiler's help, things can still go wrong. In programming, you'll encounter three main categories of errors. Understanding the difference is essential for fixing them.

1. Syntax Errors (Compile-time Errors) These are the grammar errors we just talked about. You've broken a rule of the Java language.

  • Forgetting a semicolon ; at the end of a line.
  • Using a parenthesis ) where you needed a curly brace }.
  • Misspelling a keyword, like typing publiic instead of public.

The compiler catches these for you. They are called "compile-time errors" because they are found during the compilation phase. Your IDE will usually underline these in red before you even try to compile.

2. Logic Errors This is the trickiest type of error. A logic error occurs when your code is grammatically perfect (it compiles and runs), but it doesn't do what you intended. The algorithm itself is flawed.

  • Analogy: Your chili recipe is written in perfect English, but you wrote "1 cup of salt" instead of "1 teaspoon of salt." The recipe is valid, but the result is a disaster.

You might write a program to calculate the average of three test scores. Your code adds the scores but you forget to divide by 3. The program will run without crashing, but it will give you the wrong answer. You only find logic errors by testing your program with specific inputs and checking if the output is what you expect.

3. Run-time Errors These errors happen while the program is running (during "execution"). The code is syntactically correct, and the initial logic might seem fine, but an unexpected situation causes the program to crash.

  • Analogy: Your chili recipe says, "Get the can of beans from the pantry." But when you go to the pantry, it's empty. You can't complete the step, and the whole cooking process comes to a halt.

A common example in programming is trying to divide a number by zero. Mathematically, this is undefined. In programming, it causes a run-time error that typically crashes the program. Another example is trying to read data from a file that doesn't exist.

These errors are often called exceptions. An exception is an event that disrupts the normal flow of the program. Your program is running along just fine, and then—BAM—an exceptional, unexpected event occurs, and the program stops.


Summary of Errors

Error Type When is it found? Who finds it? What happens? Example
Syntax Error During compilation The Compiler Program fails to compile. Missing a semicolon ;
Logic Error During testing You (the programmer) Program runs but gives wrong output. Adding numbers but forgetting to divide for an average.
Run-time Error While the program is running The User / System Program crashes or terminates unexpectedly. Dividing by zero.

Learning to identify and fix these three types of errors is the single most important practical skill you will develop as a programmer.

The compiler's role: checking and translating Java code.

Worked examples

Let's make these ideas concrete with a few examples. Seeing how this works in practice is the best way to learn.

Example 1

Algorithm for Calculating a Discount

Problem: Priya wants to buy a new pair of headphones that cost $150. The store is having a 20% off sale. Write a simple, step-by-step algorithm to calculate the final price she has to pay, not including sales tax.

Solution Walkthrough:

  1. 1
    Identify the Goal
    The goal is to find the final price after a discount.
  2. 2
    List the Knowns
    • Original Price: $150
    • Discount Rate: 20% (or 0.20)
  3. 3
    Break Down the Process (The Algorithm)
    • Step 1
      Calculate the discount amount. To do this, multiply the original price by the discount rate.
      • $150 * 0.20 = $30
    • Step 2
      Calculate the final price. To do this, subtract the discount amount from the original price.
      • $150 - $30 = $120
    • Step 3
      State the final answer.
      • The final price is $120.
Example 2

Identifying Programming Errors

Problem: A student, Liam, is writing a program. For each scenario below, identify whether the error is a syntax, logic, or run-time error.

  • Scenario A
    Liam writes code to calculate the area of a rectangle (width * height). He accidentally types width + height. The program runs, but for a width of 5 and height of 10, it outputs 15 instead of 50.
  • Scenario B
    Liam forgets to put a semicolon at the end of a line of code. His IDE, IntelliJ, underlines the line in red, and the program won't compile.
  • Scenario C
    Liam's program asks the user to enter their age. The program then divides 100 by the user's age. One user enters 0. The program immediately crashes.

Solution Walkthrough:

  • Scenario A is a Logic Error
    • Why: The code is syntactically correct (the compiler doesn't know you meant to multiply). It runs without crashing. However, the underlying algorithm is flawed, so it produces the wrong result. The only way Liam would find this is by testing his code and seeing that the output (15) doesn't match the expected output (50).
  • Scenario B is a Syntax Error
    • Why: Forgetting a semicolon violates the grammatical rules of the Java language. The compiler is designed to catch exactly this kind of mistake. The key clue is that the program "won't compile." If the compiler finds it, it's a syntax error.
  • Scenario C is a Run-time Error
    • Why: The code is syntactically correct and the logic works for most inputs (like age 10, 25, or 50). The error only occurs during execution when a specific, problematic value (0) is used. Division by zero is an impossible operation that the system can't handle, so it halts the program. This is a classic example of an exception that causes a run-time error.
Tracing the discount calculation algorithm.
Common error types: syntax, logic, and run-time.

Try it yourself

Ready to try a couple on your own? Don't worry about writing perfect code, just focus on the logic and the concepts.

Problem 1: The Vending Machine Algorithm

You're in the student lounge in front of a vending machine. Write a clear, step-by-step algorithm for buying a bag of chips. Think about the sequence. What happens if you try to make your selection before inserting money? Your algorithm should account for the necessary order of operations.

  • Hint: Start by listing the major actions: inserting money, making a selection, and retrieving the item. Then, think about the details. Does the machine need to check if you've inserted enough money? What are the steps for that?

Problem 2: Error Spotting

A program is supposed to convert a temperature from Fahrenheit to Celsius using the formula C = (F - 32) * 5 / 9.

A programmer writes the code, but it contains the line: celsius = fahrenheit - 32 * 5 / 9;

Due to the order of operations in math, the multiplication (32 * 5) will happen first. What kind of error is this (syntax, logic, or run-time)? How would you, the programmer, discover this error?

  • Hint: Does this code violate the rules of the Java language? Will it compile? Will it crash when it runs? Or will it just give a strange answer for a known input like 212°F (which should be 100°C)?
Vending machine algorithm: ensuring correct sequence.