Reputation:
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));
Upvotes: -1
Views: 125
Reputation: 1
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()));
Upvotes: 0
Reputation: 375
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
Upvotes: 0