Structure of a C program - Time & Space Complexity
Let's see how the time it takes to run a simple C program changes as the program size grows.
We want to know how the program's structure affects how long it runs.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
This code prints a message once and then ends.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single print statement.
- How many times: Exactly once, no loops or repeats.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the program runs in constant time, doing the same amount of work regardless of input size.
[X] Wrong: "Adding more lines of code always makes the program slower in a way that depends on input size."
[OK] Correct: Some code runs a fixed number of times no matter the input, so its time does not grow with input size.
Understanding that some parts of a program run in constant time helps you explain how programs behave and write efficient code.
"What if we added a loop that prints the message n times? How would the time complexity change?"