What is Big O of a loop?

Viewed 56307

I was reading about Big O notation. It stated,

The big O of a loop is the number of iterations of the loop into number of statements within the loop.

Here is a code snippet,

for (int i=0 ;i<n; i++)
{
    cout <<"Hello World"<<endl;
    cout <<"Hello SO";
}

Now according to the definition, the Big O should be O(n*2) but it is O(n). Can anyone help me out by explaining why is that? Thanks in adavance.

7 Answers

The fastest growing term in your program is the loop and the rest is just the constant so we choose the fastest growing term which is the loop O(n)

In case if your program has a nested loop in it this O(n) will be ignored and your algorithm will be given O(n^2) because your nested loop has the fastest growing term.

Related