I'm a CS student and really don't know that much about coding so any help would be appreciated.
I've looked at many other examples of when this error is being thrown in other code- I understand that it occurs when an attempt is made to change the collection during iteration. But I'm not doing that; the PrevGen = NowGen;
line is outside the foreach loop so I don't understand why it is throwing an error.
Code:
int months = int.Parse(Console.ReadLine());
Console.WriteLine("lifespan");
int lifespan = int.Parse(Console.ReadLine());
List<int> PrevGen = new List<int>{0};
List<int> NowGen = new List<int>();
Console.WriteLine(PrevGen.Count);
for (int i = 0; i < months; i++)
{
foreach (int bunny in PrevGen)
{
if (bunny == 2 || bunny == 3)
{
NowGen.Add(0);
if (bunny == 2) { NowGen.Add(bunny); }
}
else
NowGen.Add(bunny);
}
for (int x = 0; x <= NowGen.Count-1; x++)
{
NowGen[x]++;
}
Console.WriteLine(NowGen.Count);
PrevGen = NowGen;
}
}
}
If anyone could help me as how to write the code so that prevGen can be modified & doesn't give an error, that would be great.