Checked and unchecked arithmetic in C Sharp (C#) - Time & Space Complexity
When we use checked or unchecked arithmetic in C#, it affects how the program handles number operations that might go beyond limits.
We want to see how this choice changes the time it takes to run arithmetic operations as input size grows.
Analyze the time complexity of the following code snippet.
int SumChecked(int[] numbers) {
int total = 0;
checked {
foreach (int num in numbers) {
total += num;
}
}
return total;
}
This code adds up all numbers in an array using checked arithmetic to catch overflow errors.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number in the array to a total inside a loop.
- How many times: Once for every element in the input array.
As the array gets bigger, the program does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish adding grows in a straight line as the input size grows.
[X] Wrong: "Using checked arithmetic makes the addition slower in a way that changes how time grows with input size."
[OK] Correct: Checked arithmetic adds a small fixed cost per addition but does not change the overall pattern of how time grows with input size.
Understanding how checked and unchecked arithmetic affect performance helps you explain trade-offs clearly and shows you think about both correctness and efficiency.
"What if we replaced the checked block with an unchecked block? How would the time complexity change?"