0

This is a part of a bigger problem I'm trying to solve, but index out of range exception seems to be an invisible hurdle to me. This if loop works well in c++ but in c#, idk whats happening. Any help is appreciated. This is very important to me. Please find the root for this exception.

    namespace damn
{
class Program
{
    static void Main(string[] args)
    {

        string InputString = Console.ReadLine();
        string[] stringArray = InputString.Split(',');
        int[] intArray = new int[stringArray.Length];
        for (int i = 0; i < stringArray.Length; i++)
        {
            intArray[i] = int.Parse(stringArray[i]);
        }

        int length = stringArray.Length;

        for(int i=0; i<length; i++)
           {
             if (intArray[i] > intArray[i + 1])
                Console.WriteLine("ok");
            else
                Console.WriteLine("not ok");
           }

    }

IndexOutOfRangeException was unhandeled.But how? the logic is right, ain't it? Call me a noob or what ever, this is not the actual program, but a part of it.

input sample -

          1,2,3,4 [/enter/]
Ashwin Prasad
  • 79
  • 1
  • 12

2 Answers2

2

You have int Array[i + 1] where i goes one less than length so for last item you will have out of range as array is zero-based index; end loop 2 less then length so that intArray[i + 1] wont go out of range.

 for(int i=0; i<length-1; i++)
Adil
  • 146,340
  • 25
  • 209
  • 204
0

your second loop is out of range doens't matter if you're using C++ or C#. it's just that iin C++ you have to manage your own memory space and it doesn't throw index out of range error; so you need to know when to stop in C++.

Let's get back to your code:

for(int i=0; i<length; i++)
           {
             if (intArray[i] > intArray[i + 1])
                Console.WriteLine("ok");
            else
                Console.WriteLine("not ok");
           }

When i == length - 1 which is your last true condition, i+1 is out of range of the array because i + 1 = length; and in C# index starts from 0.

to fix just simply change your second loop condition to i < length - 1 instead of i < length

NPToita
  • 238
  • 2
  • 9