Informal Run-Time Analysis
Why this matters
Imagine you and your friend Carlos are in charge of making 100 sandwiches for a school fundraiser. You set up an assembly line: grab bread, add turkey, add cheese, wrap. You do this 100 times. It’s a lot of work, but it’s organized.
Now, imagine Carlos decides on a different method. For each of the 100 sandwiches, he grabs one slice of bread, runs to the pantry for the turkey, comes back, adds it, then runs back to the pantry for the cheese. He’s doing so much extra running!
Both of you will finish with 100 sandwiches, but his method is clearly less efficient. In programming, we face similar choices. Often, there are multiple ways to write code that produces the same correct result. How do we decide which is "better"? We can start by counting the steps. That’s exactly what we'll do today: learn to count a program's "steps" to measure its efficiency.
Concept overview
flowchart TD
A[Start: Analyze Code Snippet] --> B{Is there a loop?};
B -- No --> C[Execution count is 1];
B -- Yes --> D{Is it a nested loop?};
D -- No --> E["Count = 'n' (number of iterations)"];
D -- Yes --> F{Analyze inner and outer loops};
F --> G["Outer loop runs 'm' times"];
F --> H["Inner loop runs 'p' times"];
G --> I["Count = 'm' * 'p'"];
H --> I;
C --> Z[End];
E --> Z;
I --> Z;
Core explanation
Hello! I'm Saavi, and I'm so glad you're here. Today, we're tackling a topic that forms the foundation of writing not just correct code, but good code.
What's a "Statement Execution"?
First, let's get our terms straight. A statement is just a single action in your code. Think of it like one instruction in a recipe.
System.out.println("Go, Huskies!");
That's one statement. When your program runs this line, we call that one statement execution.
A statement execution count is simply the total number of times a statement is run during a program. If that line were inside a loop that ran 10 times, its execution count would be 10.
Why Bother Counting?
Think back to the sandwich example. Your method (the assembly line) and Carlos's method (running back and forth) both get the job done. But if you were running a sandwich shop like Subway, you'd want the most efficient process to serve customers quickly.
In programming, efficiency matters. An efficient app on your phone uses less battery. An efficient search on a website like Amazon gives you results in a split second, not a full minute. By counting statement executions, we get a simple way to measure and compare this efficiency.
Counting Executions in a Single Loop
Let's start with the most common structure: a for loop.
int n = 10;
for (int i = 0; i < n; i++) {
System.out.println("Processing item..."); // This is the statement we'll count
}
How many times will "Processing item..." be printed?
Let's trace it:
istarts at 0.0 < 10is true. Print. (1st time)ibecomes 1.1 < 10is true. Print. (2nd time)- ...
ibecomes 9.9 < 10is true. Print. (10th time)ibecomes 10.10 < 10is false. The loop stops.
The statement inside the loop executed 10 times. In general, for a loop that goes from 0 to n-1, the body executes n times. This is a fundamental pattern you should recognize immediately.
The Game Changer: Nested Loops
This is where things get interesting, and where code can suddenly become much less efficient. A nested loop is a loop inside another loop.
Imagine we're creating a coordinate grid for a simple game, printing the coordinates for every point.
int rows = 4;
int cols = 5;
for (int i = 0; i < rows; i++) { // Outer loop
for (int j = 0; j < cols; j++) { // Inner loop
System.out.println(i + ", " + j); // The statement we're counting
}
}
How many times does the println statement run?
Think about it:
- The outer loop runs for
i = 0. - Inside that single run, the inner loop runs completely. It runs for
j = 0, 1, 2, 3, 4. That's 5 times. - Then the outer loop runs for
i = 1. - The inner loop runs again, completely.
j = 0, 1, 2, 3, 4. That's another 5 times. - This repeats for
i = 2andi = 3.
So, for each of the 4 runs of the outer loop, the inner loop's statement executes 5 times.
The total count is *`rows cols**, which is4 * 5 = 20` times.
Analogy Time: Think of it like a calendar. The outer loop is the week (7 days). The inner loop is the hours in a day (24 hours). To find the total hours in a week, you don't add 7 + 24. You multiply 7 * 24. It's the same principle.
Informal Comparison
Now we can use these counts to make decisions. Let's say we have two algorithms to process some data of size n.
Algorithm A:
for (int i = 0; i < n; i++) {
// do one thing
}
Statement execution count: n
Algorithm B:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// do one thing
}
}
Statement execution count: *`n n**, or **n^2`**
If n is 10:
- Algorithm A runs its statement 10 times.
- Algorithm B runs its statement 100 times.
If n is 1,000:
- Algorithm A runs its statement 1,000 times.
- Algorithm B runs its statement 1,000,000 times!
You can see that Algorithm B gets slow very quickly as n increases. Even though both might be "correct," Algorithm A is far more efficient. This is an informal run-time comparison. We're not using a stopwatch; we're using logic and simple math to predict performance. This is a critical skill for any programmer.
See it in action
Worked examples
Let's walk through a few examples together. The key is to go slow and trace the code, just like the computer would.
Example 1: A Simple for Loop
Problem: Your classmate, Priya, wrote some code to print a list of welcome messages. How many times does the statement System.out.println("Welcome!"); execute?
public void printWelcomes(int num) {
for (int i = 1; i <= num; i++) {
System.out.println("Welcome!");
}
}
// Somewhere else in the code, it's called like this:
printWelcomes(5);
Step-by-step Solution:
- 1Identify the loop and the target statementThe loop is
for (int i = 1; i <= num; i++). The target statement isSystem.out.println("Welcome!");. - 2Determine the value of the control variableThe method is called with
printWelcomes(5), sonumis 5. The loop condition is effectivelyi <= 5. - 3Trace the loop's execution
istarts at 1.1 <= 5is true.printlnexecutes. (Count: 1)ibecomes 2.2 <= 5is true.printlnexecutes. (Count: 2)ibecomes 3.3 <= 5is true.printlnexecutes. (Count: 3)ibecomes 4.4 <= 5is true.printlnexecutes. (Count: 4)ibecomes 5.5 <= 5is true.printlnexecutes. (Count: 5)ibecomes 6.6 <= 5is false. The loop terminates.
- 4State the final countThe
printlnstatement executes exactly 5 times.
A Nested Loop for Finding Pairs
Problem: This code looks for pairs of identical numbers in an array. How many times is the if statement's condition checked if the input array has 5 elements?
public void findPairs(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) { // How many times does this check run?
// ... do something
}
}
}
}
// Called with an array of length 5.
int[] myNums = {10, 20, 30, 40, 50};
findPairs(myNums);
Step-by-step Solution:
- 1Identify the loops and the target statementWe have two nested
forloops. The target is the conditionarr[i] == arr[j]. - 2Determine the loop boundsThe input array
myNumshas a length of 5. So,arr.lengthis 5.- The outer loop runs for
ifrom 0 to 4 (i < 5). - The inner loop runs for
jfrom 0 to 4 (j < 5).
- The outer loop runs for
- 3Apply the nested loop ruleFor each one run of the outer loop, the inner loop runs completely. The statement inside the inner loop will execute
outer_iterations * inner_iterationstimes. - 4Calculate the count
- Outer loop iterations: 5 (for
i= 0, 1, 2, 3, 4) - Inner loop iterations: 5 (for
j= 0, 1, 2, 3, 4) - Total executions =
5 * 5 = 25.
- Outer loop iterations: 5 (for
- 5State the final countThe
ifconditionarr[i] == arr[j]is checked 25 times.
This is a classic n * n or n^2 pattern, where n is the length of the array.
Try it yourself
Ready to try a couple on your own? Don't worry about writing the full code, just focus on the counting.
- 1Heating UpA microwave's timer code is supposed to
beep()every second. How many times willbeep()be called by this code snippet?int start = 60; // seconds int end = 0; for (int i = start; i > end; i--) { beep(); }Hint: This loop counts down. Does that change how many times it runs? Trace the first and last values of
ithat make the conditioni > endtrue. - 2Team MatchupsA basketball league in Dallas needs to schedule games. The code below iterates through a list of teams. How many times is
scheduleGame()called, in terms ofnumTeams?int numTeams = 10; // Let's say there are 10 teams for (int team1 = 0; team1 < numTeams; team1++) { for (int team2 = team1 + 1; team2 < numTeams; team2++) { scheduleGame(team1, team2); } }Hint: This is tricky! The inner loop doesn't always start at 0. Try tracing it with a small
numTeamslike 4. Write down the pairs of(team1, team2)that get scheduled. Can you see a pattern? This is a very common and important algorithm pattern!
Practice — 8 questions
In simple terms, informal run-time analysis is about counting how many times a line of code runs to compare which of two programs is more efficient.
int n = 10;
for (int i = 0; i < n; i++) {
System.out.println("Processing item..."); // This is the statement we'll count
}
- 2.12.A: Calculate statement execution counts and informal run-time comparison of iterative statements.
- 2.12.A.1
- A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements.
flowchart TD
A[Start: Analyze Code Snippet] --> B{Is there a loop?};
B -- No --> C[Execution count is 1];
B -- Yes --> D{Is it a nested loop?};
D -- No --> E["Count = 'n' (number of iterations)"];
D -- Yes --> F{Analyze inner and outer loops};
F --> G["Outer loop runs 'm' times"];
F --> H["Inner loop runs 'p' times"];
G --> I["Count = 'm' * 'p'"];
H --> I;
C --> Z[End];
E --> Z;
I --> Z;
Read what Saavi narrates
Hi there, I'm Saavi, your guide for AP Computer Science. I'm really happy you're taking the time to dig into this topic.
So, imagine you and your friend Carlos are making one hundred sandwiches for a school fundraiser. You set up a smart assembly line... grab bread, add turkey, add cheese, wrap. You do this a hundred times. Carlos, on the other hand... for each sandwich, he runs to the pantry for turkey, comes back, then runs back to the pantry for cheese. He’s doing so much extra work!
Both of you make the sandwiches, but his method is way less efficient. In programming, we have the same issue. Multiple pieces of code can give the same right answer, but some are much, much faster than others. Today, we're learning how to count the "steps" a program takes, so we can pick the faster one.
This is called informal run-time analysis. It just means we're going to count how many times a specific instruction runs.
Let's look at a quick example. Imagine a method is called that runs a simple loop five times. The code looks something like this... a for loop where a variable, let's call it `i`, goes from one up to and including five. Inside the loop, it prints the word "Welcome!".
How many times does "Welcome!" get printed? Well, let's trace it. When `i` is one, it prints. When `i` is two, it prints. It keeps going... when `i` is five, it prints. Then `i` becomes six, and the loop stops. So, it printed five times. Simple enough.
But here's a common mistake I see all the time, especially with nested loops. That's a loop inside another loop. Students often add the loop counts instead of multiplying. If an outer loop runs 4 times, and an inner loop runs 5 times, the code inside runs twenty times, not nine. Think of it like a calendar... for each of the, say, four weeks in a month, you have seven days. The total days are four times seven, not four plus seven. Always multiply for nested loops.
Keep practicing this skill of counting. It seems simple, but it’s the first step toward writing truly professional, efficient code. You're building a great foundation. Keep up the fantastic work!
For a nested loop, the inner loop runs completely for *every single iteration* of the outer loop. You must multiply the iteration counts, not add them. `for (i=0; i<4)... for (j=0; j<5)...` means the inner code runs `4 * 5 = 20` times, not `4 + 5 = 9`.
Always think "for each outer, do all of the inner." This mindset leads directly to multiplication.
A loop `for (int i = 0; i < n; i++)` runs exactly `n` times (for i = 0, 1, ..., n-1). A loop `for (int i = 1; i <= n; i++)` also runs `n` times (for i = 1, 2, ..., n). Miscounting by one can lead to the wrong answer on a multiple-choice question.
When in doubt, trace the first two and the last one. For `i < 5`, trace `i=0`, `i=1`, then jump to `i=4` (runs) and `i=5` (stops). This confirms the boundary.
If a loop runs to `n`, the execution count is an expression involving `n`, like `n` or `n/2` or `n*n`. The answer isn't just "10" unless you were told `n=10`.
Read the question carefully. If it asks for the count in terms of `n`, your answer must include the variable `n`.
A question will be very specific: "How many times does the `println` execute?" or "How many times is the `if` condition checked?" If there are multiple lines inside a loop, make sure you're analyzing the correct one.
Highlight or underline the exact statement mentioned in the problem before you start counting.
If a loop runs `n` times and has 3 statements inside it, each statement executes `n` times. The total number of statement executions inside the loop is `3 * n`.
Calculate the loop's iteration count first. Then, multiply by the number of statements you're asked to count inside the loop.