I was doing a past paper question at school to adapt some pseudo code which checked if an input ISBN number was valid or not, into C#. I have typed the code in, yet it throws an IndexOutOfRangeException error. I am unsure how that error occurred, as this is my first time using int arrays.
I checked that the index is not negative, and I think the maximum index on the list is less than the list size (I tried changing "Count < 13" in the for loop to "Count <= 12", but to no avail).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISBNExercise
{
class Program
{
static void Main(string[] args)
{
int[] ISBN;
int Count;
ISBN = new int[13];
for(Count = 0; Count < 13; Count++)
{
Console.WriteLine("Please enter next digit of ISBN");
ISBN[Count] = Convert.ToInt32(Console.ReadLine());
}
int CalculatedDigit = 0;
int count = 1;
while (count < 13)
{
CalculatedDigit = CalculatedDigit + ISBN[Count]; //This is where the error is being thrown.
Count += 1;
CalculatedDigit = CalculatedDigit + ISBN[Count] * 3;
Count += 1;
}
while (CalculatedDigit >= 10)
{
CalculatedDigit -= 10;
}
CalculatedDigit = 10 - CalculatedDigit;
if (CalculatedDigit == 10)
{
CalculatedDigit = 0;
}
if (CalculatedDigit == ISBN[13])
{
Console.WriteLine("Valid ISBN");
}
else
{
Console.WriteLine("Invalid ISBN");
}
}
}
}