-1

I am doing a coding exercise which is :

Have the function ThreeFiveMultiples(num) return the sum of all the multiples of 3 and 5 that are below num. For example: if num is 10, the multiples of 3 and 5 that are below 10 are 3, 5, 6, and 9, and adding them up you get 23, so your program should return 23. The integer being passed will be between 1 and 100.

I am not sure where the error in my c# solution is and i'd like to have help to solve this problem thank you.

I tried this in C# but get the error : System.IndexOutOfRangeException: Index was outside the bounds of the array

using System;
using System.Linq;

class MainClass {

  public static int ThreeFiveMultiples(int num) {

    //var total = 0;

    int[] array = new int[] {};

    for(var i = num-1; i>1; i--)
    {
      if(i%5 == 0 || i%3 == 0)
      {
        array[i] = i;
      }
    }

    return array.Sum();
  }

This is the solution in javascript

function ThreeFiveMultiples(num) { 
    var arr = [];
    var tot=0;
   for(var i=num-1; i>1; i--){
        if(i%5===0 || i%3===0){
            arr.push(i);
        }
    }
    for(var i=0; i<arr.length; i++){
        tot = tot+ arr[i];
    }
    return tot;
}
codetime
  • 209
  • 2
  • 9
  • I believe it's because your using a backwards for loop which for example in this case `i` would be `9` and I believe doing `arr[9]` on a empty array will case a error (`Index was outside the bounds of the array`) I don't really know c# very much so I can't really fix it for you. – Harry Kruger Jan 27 '21 at 23:04
  • This `new int[] {};` creates an array of size `0` so it will throw that exception as soon as you try to access any element in the array. In `C#` you can use a `List` which is a dynamic array similar to the one you are using in `JS` – StaticBeagle Jan 27 '21 at 23:05
  • 2
    Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Charlieface Jan 27 '21 at 23:07

1 Answers1

0

In javascript array.push will increase the size of the array and add the item.

This does not work with C#. Use List instead, which can convert to an array, if you need.

public static int ThreeFiveMultiples(int num) {

    List<int> numbers = new List<int>();

    for(var i = num-1; i>1; i--)
    {
        if(i%5 == 0 || i%3 == 0)
        {
            numbers.Add(i);
        }
   }

    // Turn it into an array, for the hell of it.
    int[] arr = numbers.ToArray();

    return numbers.Sum(i => i);
}
Neil W
  • 7,670
  • 3
  • 28
  • 41