As said earlier, the problem is in the line: for (int i = 0; i <= n; i++) .
To solve this problem, I would have approached a bit from the other side. When iterating through a collection, you can use not third-party variables that may be erroneous, but the length of the array. You used it in the first for .
For example, if n = 10 , and in the array you have nine elements, then you will again get an exception. Suddenly the variable n has changed somewhere?
You can use Length (for lists Count ). Like this:
for (int index = 0; index < arr.Length; index++) {...} // Π² ΡΠ»ΡΡΠ°Π΅ Ρ ΠΌΠ°ΡΡΠΈΠ²ΠΎΠΌ for (int index = 0; index < lst.Count; index++) {...} // Π² ΡΠ»ΡΡΠ°Π΅ ΡΠΎ ΡΠΏΠΈΡΠΊΠΎΠΌ
The foreach, in method for iterating a colection is also very convenient if you do not need indexes, in which case you do not need to worry about knowing the number of array elements:
foreach (var item in array) {...}
However, it should not be used to add or remove items from the original collection to avoid unforeseen side effects. If you need to add or remove items from the original collection, you should use a for loop.
foreach bit simpler, since it works for arrays or collections of objects that implement the IEnumerable or IEnumerable<T> interface from System.Collections.Generic .
But this is not all that can facilitate the work of the programmer, there is also an Enumerable.Sum method that calculates the sum of a sequence. And you do not have to go through all the elements of the collection. For example:
double sum = a.Sum(); // ΡΡΠΌΠΌΠ° ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² ΠΠ°ΡΠ΅Π³ΠΎ ΠΌΠ°ΡΡΠΈΠ²Π°
You can also note the Enumerable.Aggregate method, which applies an aggregate function to a sequence. For example, the receipt of the amount will be as follows:
double sum = a.Aggregate((result, item) => result + item);