Floating point types (float, double, decimal) in C Sharp (C#) - Time & Space Complexity
When working with floating point types like float, double, and decimal, it's helpful to understand how the time to perform calculations changes as the amount of data grows.
We want to know how the time needed to process many numbers scales as we increase the number of values.
Analyze the time complexity of the following code snippet.
float[] numbers = new float[n];
float sum = 0f;
for (int i = 0; i < n; i++)
{
sum += numbers[i];
}
return sum;
This code sums up all the float numbers in an array of size n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each float number to the sum inside a loop.
- How many times: Exactly n times, once for each element in the array.
As the number of float values increases, the total additions increase at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with the input size. Double the numbers, double the work.
Time Complexity: O(n)
This means the time to sum all numbers grows in a straight line with how many numbers there are.
[X] Wrong: "Using decimal instead of float makes the summing slower in a way that changes the time complexity."
[OK] Correct: While decimal operations can be slower per calculation, the number of operations still grows linearly with input size, so the overall time complexity remains the same.
Understanding how loops over floating point numbers scale helps you explain performance clearly and shows you know how data size affects program speed.
"What if we changed the code to sum numbers in a nested loop over the same array? How would the time complexity change?"