String input and output in C - Time & Space 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.
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 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).
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 |
|---|---|
| 10 | About 10 character reads and 10 prints |
| 100 | About 100 character reads and 100 prints |
| 1000 | About 1000 character reads and 1000 prints |
Pattern observation: The number of operations grows directly with the string length.
Time Complexity: O(n)
This means the time to read and print the string grows in a straight line with the string length.
[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.
Understanding how string input and output time grows helps you explain how programs handle user data efficiently.
"What if we used fgets() instead of scanf() to read the string? How would the time complexity change?"