Writing first C program - Time & Space Complexity
When writing your first C program, it is helpful to understand how the program's steps grow as the input changes.
We want to see how the time the program takes changes when we run it with different inputs.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
This code prints a simple greeting message once and then ends.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Printing the message once.
- How many times: Exactly one time.
Since the program prints the message only once, the time it takes does not change with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[X] Wrong: "The program takes longer if I run it on a bigger input or with more input."
[OK] Correct: This program does the same single action every time, so input size or computer speed does not change how many steps it takes.
Understanding that some programs run in constant time helps you explain how simple tasks behave, which is a useful skill in coding interviews and real projects.
"What if we added a loop to print the message n times? How would the time complexity change?"