Basic formatting in C++ - Time & Space Complexity
We want to see how the time a program takes changes as we give it more data.
For basic formatting, we ask: how does the program's work grow when formatting more items?
Analyze the time complexity of the following code snippet.
#include <iostream>
#include <vector>
void printNumbers(const std::vector<int>& nums) {
for (int num : nums) {
std::cout << "Number: " << num << std::endl;
}
}
This code prints each number in a list with a label before it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every number in the list.
As the list gets bigger, the program prints more lines, so it takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print lines |
| 100 | 100 print lines |
| 1000 | 1000 print lines |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time grows in a straight line with the number of items to print.
[X] Wrong: "Printing each item takes the same time no matter how many items there are."
[OK] Correct: Actually, printing each item adds up, so more items mean more total time.
Understanding how loops affect time helps you explain how your code handles bigger data smoothly.
"What if we printed only every other number? How would the time complexity change?"