0

I am trying to write a simple programm that displays multiples from 5 up to 1000. But the console is empty when executed. It is not clear to me why this is happening. I am still a beginner so please excuse this maybe stupid question. Thank you!

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

for (int i=1; i < nums.Length; i++)
{
    //Checks if number is divisible by 5
    if (i%5 == 0)
    {
        //Creates Array input in right index
        int tst = i / 5 - 1;

        //Writes i to array
        nums[tst] = i;
    }
}

Console.WriteLine(String.Join("; ", nums));
smn.tino
  • 2,272
  • 4
  • 32
  • 41
  • 2
    Possible duplicate of [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) – Ňɏssa Pøngjǣrdenlarp Jul 29 '18 at 13:42
  • Change `nums` from an array to a `List`. Then use `nums.Add`. – mjwills Jul 29 '18 at 13:47

2 Answers2

1

Lenght of your nums array is zero. Your getting error for this. For your example you have to create array which is min 200 lenght like that;

int[] nums = new int[200]; // index will be 0 to 199
Waayd
  • 365
  • 3
  • 14
  • Thank you! I always put the 1000 in the curly brackets ;/ It's solved now –  Jul 29 '18 at 13:50
0

Arrays have a fixed length once they've been initialised and in this case the array you're creating has zero length (e.g. empty).

If you need to add to it dynamically, you're better off creating a List, and then when you need to use it, cast it into an array, like this:

List<int> nums = new List<int>();
int countTarget = 1000;

for (int i = 1; i < countTarget; i++)
{
    //Checks if number is divisible by 5
    if (i % 5 == 0)
    {
        //Writes i to list
        nums.Add(i);
    }
}

Console.WriteLine(String.Join("; ", nums.ToArray()));