fork download
  1. public class OddNumberSum {
  2. public static void calculateSum() {
  3. List<Integer> oddNumbers = new List<Integer>(); // List to store odd numbers
  4. Integer num = 1; // Start from 1
  5. Integer sum = 0; // Variable to store the sum
  6. Integer position = 0; // Position index for the list
  7.  
  8. // Use a while loop to add odd numbers to the list
  9. while (num <= 20) {
  10. if (num % 2 != 0) { // Check if the number is odd
  11. oddNumbers.add(num);
  12. }
  13. num++; // Increment number
  14. }
  15.  
  16. // Debug log to print the list of odd numbers
  17. System.debug('Odd Numbers List: ' + oddNumbers);
  18.  
  19. // Loop through the list and sum only numbers at even positions
  20. for (Integer i = 0; i < oddNumbers.size(); i++) {
  21. if (i % 2 != 0) { // Check if index is even-positioned (1-based)
  22. sum += oddNumbers[i];
  23. }
  24. }
  25.  
  26. // Print the final sum in the debug log
  27. System.debug('Sum of numbers at even positions: ' + sum);
  28. }
  29. }
  30.  
  31.  
Success #stdin #stdout #stderr 0.02s 9020KB
stdin
Standard input is empty
stdout
Object: UndefinedObject error: did not understand #OddNumberSum
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
UndefinedObject class(Object)>>doesNotUnderstand: #OddNumberSum (SysExcept.st:1448)
UndefinedObject>>executeStatements (prog:1)
stderr
./prog:2: parse error, expected '}'
./prog:10: expected expression
./prog:21: expected expression