0
0
Cprogramming~5 mins

Constants and literals - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constants and literals
O(1)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

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
10About 3 operations
100About 3 operations
1000About 3 operations

Pattern observation: The number of steps does not grow with input size; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter how big the input is.

Common Mistake

[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.

Interview Connect

Understanding that constants and literals do not affect time growth helps you focus on parts of code that really change with input size.

Self-Check

"What if we replaced the constant with a loop that adds numbers repeatedly? How would the time complexity change?"