Structure of a C++ program - Time & Space Complexity
Let's see how the time needed to run a simple C++ program changes as we add more instructions.
We want to know the program's running time behavior with respect to input size.
Analyze the time complexity of the following code snippet.
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
This program prints a message once and then ends.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Printing a single message once.
- How many times: Exactly one time.
The program has no input-dependent operations; all work is fixed and executes once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 simple instructions |
| 100 | 5 simple instructions |
| 1000 | 5 simple instructions |
Pattern observation: The time is constant regardless of input size, O(1). No repeated work based on input.
Time Complexity: O(1)
This means the running time is constant, independent of input size.
[X] Wrong: "Time complexity grows with the number of lines of code (O(n))."
[OK] Correct: Time complexity describes asymptotic growth with input size n, not source code size. Fixed operations are always O(1).
Understanding how simple programs behave helps build a strong base for analyzing bigger code later.
"What if we added a loop that prints the message n times? How would the time complexity change?"