Search⌘ K
AI Features

Example: Measuring Time Complexity—Single Loop

Explore how to analyze the time complexity of simple for loops by breaking down operations and calculating iterations. This lesson helps you understand asymptotic analysis and apply Big O notation to determine running time complexity for coding challenges.

Let’s now calculate the running time complexity of a more complex program. We will split the code into individual operations and then compute the number of iterations.

A simple for loop of size n

Here is an example of a simple loop of size n:

C# 9.0
int n = 10; // Just as an example, 'n' can be anything
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += 1;
}
System.Console.WriteLine(sum);

Operation

Number of Executions

n = 10

11

sum = 0

11

for (int i = 0; i < n; i++)

11

i=0

11

i=1

11

i=2

11

...

i=n-1

11

sum+=1

nn

System.Console.WriteLine(sum)

11

Note: While for (int i = 0; i < n; i++) executes only once, its execution cost is nn. ...

Running time