AP® Computer Science A · Unit 1 · Topic 1.1

Algorithms and the Path a Program Takes

An algorithm is a precise, ordered list of steps that solves a problem, and a program executes those steps one statement at a time, in order, from the first line to the last.

A person can skip steps and still land on the right answer, filling gaps with judgment. A computer has none of that judgment. It does exactly what it's told, in exactly the order it's told, so every step has to be spelled out: what to do, with what value, and in what order. That full, unambiguous set of steps is the algorithm. The code you type in Java is just one way of writing that algorithm down so the computer can carry it out.

Once a program starts, it runs one statement at a time, top to bottom, finishing each line before moving to the next, until it hits the end of the method or program. There's no guessing about order and no skipping ahead: the third line runs only after the first two have finished, using whatever values they left behind. This strict, linear path is why tracing code works: you can always predict output by walking the statements in the order they appear.

This matters because writing Java code and designing the algorithm are different jobs. Typing statements is just translating a plan into syntax; if the plan itself is wrong, the code can compile, run without errors, and still produce the wrong answer, because it's faithfully executing the wrong sequence of steps. Good algorithm design also looks ahead to generality: a plan built for one specific input often breaks on others, so a real algorithm is written to work for any valid input, not just the example you first imagined. That shift, from one case to all cases, is what the rest of the unit builds on as you start handling variables, expressions, and objects that can hold different values each time.

Key terms

Algorithm
A precise, ordered sequence of steps that solves a problem or completes a task.
Statement
A single complete instruction in Java that the program executes as one step.
Sequential execution
Running statements one at a time, in the order they appear, from top to bottom.
Trace
Following a program's statements in execution order to determine the values and output it produces.

Watch it explained

  1. How it worksHow does a program run one statement at a time, top to bottom, until it reaches the end?
  2. Worked exampleTrace the order the statements run in a program that sets x to 4, doubles it, then prints x.
  3. Common mistakeWhy isn't writing the code the same job as designing the algorithm first?
  4. Going furtherWhat changes about an algorithm when the same steps have to work for any input, not one?

Check yourself

Your turn1 of 2
A program sets x to 7, then doubles it, then prints x. What value does it print?

End of topic.