2

I'm working on understanding big O notation a little bit better and got stumped on this problem in class.

If I had a for loop with a constant number of iterations that simply prints something to the console on each iteration:

for(int i=1; i<10; i++)
{
   cout << "Hello!" << endl; 
}

What would the big O notation for this snippet of code be? The line that writes to the console takes 1 unit of time, and I would multiply this by the number of times it would be executed - in this case 10 - so I would get O(10). However, this just reduces to O(1).

Is this a correct analysis?

banna
  • 165
  • 11
  • 1
    Yes, it's correct. Another interpretation will be that the code doesn't depend on input at all. – TYeung Sep 02 '21 at 13:38
  • Okay - I wanted to double check because my teacher was saying something about it being O(N). That wouldn't be possible in this case right? I think she may have misspoke. – banna Sep 02 '21 at 13:39
  • 1
    What even is N in this case? – TYeung Sep 02 '21 at 13:40
  • I believe she thought the I<10 was actually I – banna Sep 02 '21 at 13:41
  • I am not sure about the context so I can't really tell, but for the particular snippet you provided, it must be O(1) instead of O(N) – TYeung Sep 02 '21 at 13:42

1 Answers1

3

Even for a loop like this:

for (int i = 0; i < 1000000; i++) {
  cout << i << '\n';
}

It's technically still O(1). I am not going to go through the formal definition of Big O notation here. But in simple words, big O notation measures how fast the running time grows with respect to input. In this case, the theoretical runtime should be the same no matter what the input is. (in fact there isn't even input). So your analysis is correct.

TYeung
  • 2,579
  • 2
  • 15
  • 30