0
0
Cprogramming~5 mins

Writing first C program - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing first C program
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Printing the message once.
  • How many times: Exactly one time.
How Execution Grows With Input

Since the program prints the message only once, the time it takes does not change with input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The number of operations stays the same no matter the input size.

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: "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.

Interview Connect

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.

Self-Check

"What if we added a loop to print the message n times? How would the time complexity change?"