Menu
Coddy logo textTech

Challenge: Sum of numbers

Part of the Fundamentals section of Coddy's Dart journey — lesson 93 of 94.

challenge icon

Challenge

Easy

In this challenge, you'll create a function that calculates the sum of numbers in a list based on certain conditions.

You have a list of integers, and you need to complete the sumWithCondition function that adds up only the numbers that meet specific criteria.

The function should:

  • Calculate the sum of all numbers in the list that are greater than the threshold value
  • Stop adding numbers immediately after the sum exceeds the maxSum value (the final sum may be greater than maxSum)
  • Return the final sum

Important: The function stops adding numbers after adding a number that causes the sum to exceed maxSum. This means the final result can be greater than maxSum.

Example: If numbers greater than threshold are [15, 20, 25, 30] and maxSum is 50:

  • Add 15: sum = 15 (continue)
  • Add 20: sum = 35 (continue)
  • Add 25: sum = 60 (exceeds 50, so stop here)
  • Result: 60 (not 50)

Try it yourself

void main() {
  // Test cases
  List<int> numbers = [5, 10, 15, 20, 25, 30];
  
  // Sum numbers greater than 12, with max sum of 50
  int result = sumWithCondition(numbers, 12, 50);
  print('Sum of numbers > 12 (max 50): $result');
  
  // Sum numbers greater than 8, with max sum of 100
  result = sumWithCondition(numbers, 8, 100);
  print('Sum of numbers > 8 (max 100): $result');
}

// TODO: Complete this function to sum numbers based on conditions
int sumWithCondition(List<int> numbers, int threshold, int maxSum) {
  int sum = 0;
  
  // TODO: Loop through the numbers list
  // TODO: Add only numbers greater than threshold to sum
  // TODO: Stop adding if sum exceeds maxSum
  
  return sum;
}

All lessons in Fundamentals