-3

I need some help with this code. I'm playing with this for a couple of hours and got nothing. So I'm asking for help from you guys.

The Array[b] was always returns out of bounds exception. I don't know why.

{
    int[] Array = new int[6];
    Array[0] = c;
    Array[1] = d;
    Array[2] = e;
    Array[3] = f;
    Array[4] = g;

    int a = 0;
    int b = 1;
    int temp = 0;

    for (int counter = 0; counter < Array.Length; counter++)
    {
        for (int counter2 = 0; counter2 < Array.Length; counter2++)
        {
            if (Array[a] > Array[b])
            {
                Console.WriteLine("{0} is Greater Than {1}, Swapping ({0},{1})", Array[a], Array[b]);
                temp = Array[a];
                Array[a] = Array[b];
                Array[b] = temp;
                Console.WriteLine("");
            }

            else
            {
                Console.WriteLine("{0} is Less Than {1}, Retain Value Position", Array[a], Array[b]);
                Console.WriteLine("");
            }

            a += 1;
            b += 1;

        }

        a = 0;
        b = 0;
    }
    for (int counter = 0; counter < Array.Length; counter++)
    {
        Console.Write(Array[counter] + " ");
    }

    Console.WriteLine("Final Position");
    return a;
}

Thanks, this is my code i hope any one of you can help me.

Subhan
  • 1,544
  • 3
  • 25
  • 58
JavaNoob
  • 1
  • 2
  • 4
    have you tried to debug your code? –  Feb 02 '15 at 12:34
  • Just try step by step in debugger! Anyway b is initialized to 1 and incremented one by one Array.Length - 1 times (then it'll reach Array.Length...but last element index is Array.Length - 1. BTW why you have a and b if you also use counter and counter2? – Adriano Repetti Feb 02 '15 at 12:35

2 Answers2

0

You are comparing one element to the next, so if you've arrived at the last element, there is no "next" element and you're out of bounds.

Change the inner loop to only go until Length - 1 to prevent this:

for (int counter = 0; counter < Array.Length; counter++)
{
    for (int counter2 = 0; counter2 < Array.Length - 1; counter2++)
    // ... 
}
Rik
  • 28,507
  • 14
  • 48
  • 67
0

before incrementing b, check if you are in the last index of the array, because you start b at 1 instead of 0, so it will go out of bounds if you enter the block while looping over the last array index.

Veverke
  • 9,208
  • 4
  • 51
  • 95
  • IMO he doesn't need to check bounds here, values (with right algorithm) are well-known, as you don't check bounds in for (int i=0; i < a.Length; ++i) – Adriano Repetti Feb 02 '15 at 12:38