How to find sum of a list of numbers in Dart
Dart is an open-source programming language developed by Google. Finding the sum of a list is essential in various applications, from calculating total costs in financial applications to determining aggregate data in analytics, making it a fundamental operation in data processing and manipulation tasks.
Calculating the sum
We can calculate the sum of a list of numbers by using a loop and maintaining a variable to accumulate the sum of all elements in the list. We can also use the reduce method from the dart:core library, or use a recursive approach to solve the problem.
Iterative approach
We can use a very basic iterative approach to solve this problem. In the code below, we defined the sumUsingLoop funtion that takes a list of integers numbers and returns an integer (int) as the sum.
int sumUsingLoop(List<int> numbers) {int sum = 0;for (int number in numbers) {sum += number;}return sum;}void main() {List<int> numbers = [1, 2, 3, 4, 5];int result = sumUsingLoop(numbers);print('Sum of numbers: $result'); // Output: Sum of numbers: 15}
Line 2: This line initializes a variable named
sumand sets its value to0. This variable will store the sum of the elements in the inputnumbersslice.Line 3: A
forloop that iterates over each element in thenumberslist. During each iteration, the value of the current element is assigned to the variablenumber, and the value of the current element (number) is added to thesumvariable.Line 6: The function returns the final value of the
sumvariable, which represents the sum of all elements in the inputnumbersslice.
The reduce method
In Dart, the reduce method is available on an iterable (such as a list) and allows us to combine elements in the list. It takes a callback function as an argument, which is applied to each element in the list, reducing the list to a single value. In this case, we use the reduce method to calculate the sum of all elements in the input list of numbers.
int sumUsingReduce(List<int> numbers) {return numbers.reduce((value, element) => value + element);}void main() {List<int> numbers = [1, 2, 3, 4, 5];int result = sumUsingReduce(numbers);print('Sum of numbers: $result'); // Output: Sum of numbers: 15}
Line 1: The
sumUsingReducefunction takes a list of integers (numbers) as input.Line 2: The
reducemethod iterates through each list element, cumulatively adding them to calculate the final sum. The function returns this sum as the result.Lines 6–8: In the
mainfunction, we create a list of numbers[1, 2, 3, 4, 5]. Then call thesumUsingReducefunction with this list, storing the result in the variableresult. Finally, we print the sum of the numbers to the console.
Recursive approach
In the code below, the sumListRecursive function calculates the sum of a list of integers using recursion.
int sumListRecursive(List<int> numbers) {if (numbers.isEmpty) {return 0;}return numbers.first + sumListRecursive(numbers.sublist(1));}void main() {List<int> numbers = [1, 2, 3, 4, 5];int result = sumListRecursive(numbers);print('Sum of numbers: $result'); // Output: Sum of numbers: 15}
Line 1: This line defines a function named the
sumListRecursivethat takes a list of integers (numbers) as its input parameter. The function returns an integer, the sum of all elements in the input list.Lines 2–4: This line checks whether the input list
numbersis empty using theisEmptyproperty. If the list is empty, there are no elements to sum. In that case, the function returns0as the sum (base case of the recursion).Line 5: This line is the recursive step of the function.
numbers.firstreturns the first element of the listnumbers. This element is added to the sum of the rest of the list.numbers.sublist(1)returns a new list that contains all elements of the original listnumbers, except for the first element. In other words, it returns a list with all elements from index 1 to the end of the list.
Complexity
All three methods have a time complexity of reduce method have efficient space complexity, using only a fixed amount of additional space
Iterative | Reduce | Recursive | |
Time complexity | O(n) | O(n) | O(n) |
Space complexity | O(1) | O(1) | O(n) |
Conclusion
We can choose the best method for our coding style and performance needs. Both the iterative and reduce methods are more space-efficient, while the recursive approach offers an alternative way to solve the problem using a different approach.
Free Resources