AP CSA Unit 1.1: Sequential Execution Code Tracing Practice
Share
Practice Question
int a = 10;
int b = 4;
System.out.println(a + b);
a = a - b;
System.out.println(a * b);
Key Concept: Sequential Execution
Sequential execution means statements execute in order from top to bottom. When a variable is reassigned, its old value is replaced.
int x = 5; // x is 5
x = x + 3; // x is now 8 (old value gone)
x = x * 2; // x is now 16 (8 is gone)
Key insight: When you see System.out.println(), that output happens immediately with the current values of variables at that moment. Later changes don't affect earlier output.
Step-by-Step Trace
| Line | Code | a | b | Output |
|---|---|---|---|---|
| 1 | int a = 10; | 10 | - | |
| 2 | int b = 4; | 10 | 4 | |
| 3 | println(a + b); | 10 | 4 | 14 |
| 4 | a = a - b; | 6 | 4 | |
| 5 | println(a * b); | 6 | 4 | 24 |
Final output: 14, then 24
The key: Line 3 uses the original value of a (10), but Line 5 uses the updated value (6) because Line 4 changed it.
Common Mistakes
This comes from printing just a instead of a * b. Line 5 prints a * b = 6 * 4 = 24, not just a.
Using the original value of a (10) for both calculations. By Line 5, a has been reassigned to 6.
The most common mistake: getting the first output correct but forgetting to update a's value after Line 4.
Thinking Line 3 prints a after Line 4's change. But Line 3 executes before Line 4, so a is still 10.
Practice Technique
Always create a table when tracing code. This forces you to:
- Process each line individually
- Update variables when they change
- Record output when it happens
- Never lose track of current values
Use this on every code tracing question!
Additional Examples
int x = 5;
System.out.println(x); // Output: 5
x = x + 3;
System.out.println(x); // Output: 8
x = x * 2;
System.out.println(x); // Output: 16
int a = 7;
int b = 3;
int temp = a; // temp = 7
a = b; // a = 3
b = temp; // b = 7
System.out.println(a + " " + b); // Output: 3 7
Related Topics
- Section 1.2: Variables and Data Types (understanding variable storage)
- Section 1.3: Expressions and Output (more complex expressions)
- Section 1.4: Assignment Statements (compound assignments)
- Section 2.1: Selection and Iteration (complex execution order)
Ready to Level Up Your AP CSA Skills?
Get personalized help or access our complete question bank
Premium Question Bank - Coming Soon! Schedule 1-on-1 Tutoring300+ Unit 1 questions • Expert tutoring with 1,700+ hours experience • 5.0 rating