Created
September 11, 2023 04:18
-
-
Save admir-live/032a4d282aa9673dcb3e31ca47bf0fd4 to your computer and use it in GitHub Desktop.
Calculates the sum of elements in a list between two indices using recursion.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// Calculates the sum of elements in a list between two indices using recursion. | |
| /// </summary> | |
| /// <param name="numbers">The list of numbers.</param> | |
| /// <param name="startIndex">The starting index for the sum.</param> | |
| /// <param name="endIndex">The ending index for the sum.</param> | |
| /// <param name="accumulatedSum">The current accumulated sum (used for recursion).</param> | |
| /// <returns>The sum of elements between the specified indices.</returns> | |
| public static int CalculateSumBetweenIndices(List<int> numbers, int startIndex, int endIndex, int accumulatedSum = 0) | |
| { | |
| if (startIndex > endIndex) return accumulatedSum; | |
| if (startIndex < 0 || startIndex >= numbers.Count || endIndex < 0 || endIndex >= numbers.Count) | |
| { | |
| throw new ArgumentOutOfRangeException("Indices are out of the range of the list."); | |
| } | |
| accumulatedSum += numbers[startIndex]; | |
| return CalculateSumBetweenIndices(numbers, startIndex + 1, endIndex, accumulatedSum); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment