Search⌘ K
AI Features

Example 1: Measuring Time Complexity of a Single Loop Algorithm

Explore how to accurately measure the time complexity of a single loop algorithm in C# by counting primitive operations such as initialization, increments, and tests. Understand how these operations contribute to the overall running time and learn to express it as a function of input size n.

In the previous lesson, you calculated the time complexity of the algorithm implemented in a simple C# program.

A for

...
C#
using System;
namespace Chapter_1
{
class Example1
{
static void Main(string[] args)
{
int n = 10;
int sum = 0;
for (int i = 0; i < n; i++)
sum += 2;
Console.Write(sum);
return;
}
}
}

Count the number of primitive operations in the above program. Skip the non-executable lines, and go to lines 8 and 9 where variable initializations are taking place. They account for one primitive operation each.

Line 10 is a loop statement. To count the number of primitive operations on that line, you must dissect it into its constituents: the initialization, the ...