When i was trying to read input from the user it throws an exception of type
'System.ArgumentOutOfRangeException'
after reading the first number from user.
class Program
{
static void Main(string[] args)
{
// Variable Declaration
List<int> Marks = new List<int>();
int i, Sum = 0, Avg;
for (i = 0; i <= 3; i++)
{
Console.WriteLine("Enter Marks of Subject :");
**I'm getting an Exception here
It just reads one subjects marks and then throws exception
Marks[i] = int.Parse(Console.ReadLine());
Sum = Sum + Marks[i];**
}
Avg = Sum / 4;
Console.WriteLine("Your Total is {0} \n\nAverage is {1}", Sum, Avg);
Console.ReadLine();
}
}
}
[This is the Exception i'm getting]
When you enter your for
loop the list Marks
is empty.
So on your first iteration, i
equals 0, but you can't set Marks[i]
because there is no Marks[0]
. It's an empty collection.
Perhaps what you want instead of
Marks[i] = int.Parse(Console.ReadLine());
is
Marks.Add(int.Parse(Console.ReadLine()));
To simplify a little bit:
var mark = int.Parse(Console.ReadLine());
Marks.Add(mark);
Sum = Sum + mark;
Or instead of adding each mark to Sum
one at a time you could just wait until the for
loop finishes and do
Sum = Marks.Sum();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.