Input and output using cin and cout in C++ - Time & Space Complexity
When we use input and output commands like cin and cout, it's important to know how the time taken grows as we handle more data.
We want to understand how the program's running time changes when reading or writing more values.
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++) {
int x;
cin >> x;
cout << x << '\n';
}
return 0;
}
This code reads an integer n, then reads and prints n integers one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that reads and prints each integer. - How many times: Exactly
ntimes, wherenis the input size.
Each number read and printed takes about the same time, so total time grows as we handle more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and 10 writes |
| 100 | About 100 reads and 100 writes |
| 1000 | About 1000 reads and 1000 writes |
Pattern observation: The total work grows directly with the number of inputs; doubling n roughly doubles the time.
Time Complexity: O(n)
This means the time to read and print grows in a straight line with the number of inputs.
[X] Wrong: "Reading or printing each number takes constant time, so the whole program is always super fast regardless of input size."
[OK] Correct: While each step is quick, doing many steps adds up, so more inputs mean more total time.
Understanding how input and output scale helps you write programs that handle large data smoothly and shows you can think about efficiency clearly.
"What if we read all inputs first into an array, then print them after the loop? How would the time complexity change?"