Constants and literals - Time & Space Complexity
When we use constants and literals in C code, we want to know how they affect the program's speed.
We ask: Does using constants or fixed values change how long the program takes as input grows?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int main() {
const int x = 5;
int y = 10;
int sum = x + y;
printf("Sum is %d\n", sum);
return 0;
}
This code adds two numbers where one is a constant and prints the result.
Look for loops or repeated steps that happen many times.
- Primary operation: Simple addition and print statement.
- How many times: Runs only once, no loops or repetition.
Since the code does not repeat or loop, the time it takes stays the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3 operations |
| 100 | About 3 operations |
| 1000 | About 3 operations |
Pattern observation: The number of steps does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[X] Wrong: "Using constants makes the program faster as input grows."
[OK] Correct: Constants do not change speed with input size because they are fixed values used once, not repeated operations.
Understanding that constants and literals do not affect time growth helps you focus on parts of code that really change with input size.
"What if we replaced the constant with a loop that adds numbers repeatedly? How would the time complexity change?"