Using cout for output in C++ - Time & Space Complexity
Let's see how the time it takes to print messages with cout changes as we print more lines.
We want to know: How does printing many lines affect the program's running time?
Analyze the time complexity of the following code snippet.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cout << "Line " << i << endl;
}
return 0;
}
This code prints "Line 0" to "Line n-1" one by one using cout.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Printing a line with
coutinside the loop. - How many times: Exactly
ntimes, once per loop iteration.
Each extra line means one more print operation, so the time grows steadily as we add lines.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The time to print grows directly with the number of lines.
Time Complexity: O(n)
This means if you print twice as many lines, it takes about twice as long.
[X] Wrong: "Printing many lines is instant and does not affect time."
[OK] Correct: Each print takes time, so more lines mean more time spent printing.
Understanding how output operations scale helps you write efficient programs and explain performance clearly.
"What if we replaced cout with a function that prints all lines at once? How would the time complexity change?"