Console.WriteLine and Write methods in C Sharp (C#) - Time & Space Complexity
When using Console.WriteLine and Console.Write methods, it's helpful to understand how the time to print grows as we print more text.
We want to know how the program's running time changes when printing longer or more pieces of text.
Analyze the time complexity of the following code snippet.
string[] words = {"apple", "banana", "cherry"};
foreach (string word in words)
{
Console.Write(word + " ");
}
Console.WriteLine();
This code prints each word from an array on the same line separated by spaces, then moves to the next line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each word in the array and printing it.
- How many times: Once for each word in the array.
As the number of words increases, the program prints more times, so it takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 print calls |
| 100 | About 100 print calls |
| 1000 | About 1000 print calls |
Pattern observation: The time grows directly with the number of words; doubling words doubles print calls.
Time Complexity: O(n)
This means the time to print grows in a straight line with the number of items printed.
[X] Wrong: "Printing multiple items at once is always constant time."
[OK] Correct: Each item printed requires its own operation, so more items mean more time.
Understanding how output operations scale helps you reason about program speed and efficiency in real tasks.
"What if we replaced the loop with a single Console.WriteLine that joins all words? How would the time complexity change?"