0
0
Cprogramming~5 mins

String input and output in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String input and output
O(n)
Understanding Time Complexity

When working with strings in C, it's important to know how the time to read or print a string grows as the string gets longer.

We want to understand how the program's work changes when the input string size changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

int main() {
    char str[1000];
    scanf("%999s", str);  // Read a string safely
    printf("%s", str); // Print the string
    return 0;
}
    

This code reads a string from the user and then prints it back to the screen.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Reading and printing each character of the string one by one.
  • How many times: Once for each character in the string until the end (null character).
How Execution Grows With Input

As the string gets longer, the program reads and prints more characters, so the work grows with the string length.

Input Size (n)Approx. Operations
10About 10 character reads and 10 prints
100About 100 character reads and 100 prints
1000About 1000 character reads and 1000 prints

Pattern observation: The number of operations grows directly with the string length.

Final Time Complexity

Time Complexity: O(n)

This means the time to read and print the string grows in a straight line with the string length.

Common Mistake

[X] Wrong: "Reading or printing a string always takes the same time no matter how long it is."

[OK] Correct: The program must handle each character, so longer strings take more time.

Interview Connect

Understanding how string input and output time grows helps you explain how programs handle user data efficiently.

Self-Check

"What if we used fgets() instead of scanf() to read the string? How would the time complexity change?"