Arrays and for loops

Nov 29, 2019 at 4:14am
Why does printing an array take so much longer than checking what is in an element using a for loop. For instance.
1
2
3
4
5
6
7
8
9
10
11
12
  for (int i = 0; i <10000; i++) 
      {cout << i << endl;} 

Compared to 

   for (int i = 0; i <10000; i++) 
      {
       if (i % 2 == 0)
      {
       cout << i << endl;} 
     } 


The second still takes a while but not as long as the firs but I done understand why. Are they both not iterating through the entire array? So why does it differ?
Nov 29, 2019 at 4:18am
You are not counting the time it takes to print output, which is significant. Especially with that endl in there, which causes a stream flush every time.

In your first loop, you print and flush N times.

In your second loop, you only print and flush N/2 times.

Hope this helps.


[edit] Change endl to '\n' for an improvement.
Last edited on Nov 29, 2019 at 4:21am
Nov 29, 2019 at 4:19am
I did not know those added significant times. I will look into that. Thanks for thr answer :)
Nov 29, 2019 at 5:32am
Switching to '\n' probably won't make a difference since cout is usually line-buffered if not redirected to a file. I'm not sure how to change it to be fully-buffered.
Topic archived. No new replies allowed.