Search code examples
c#foreachindexoutofboundsexception

Getting 'Index was outside the bounds of the array.' while using foreach loop in C#


I am getting "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" error at run time while trying to print values of array using foreach loop. I debugged the problem in visual studio and can see that i in foreach is going till 7 which is out of bounds. foreach loop automatically takes all the elements of an array so please help me in understanding the reason for the error? Below is the function:

    void Sort(int[] A)
    {
        for (int i = 1; i < A.Length; i++)
        {
            int key = A[i];
            int j = i - 1;
            while (j >= 0 && A[j] > key)
            {

                A[j + 1] = A[j];
                j = j - 1;
            

            }
            A[j + 1] = key;
        }

        foreach (int i in A)
            Console.Write(A[i].ToString());

    }

}

}


Solution

  • I think you misunderstood the usage of foreach loop. Change-

    foreach (int i in A)
        Console.Write(A[i].ToString());
    

    to-

    foreach (int i in A)
        Console.Write(i.ToString());
    

    In the loop above i is an element in A not the index of element. For loops will give you the index:

    for (int i = 0; i < A.Length; i++)
        Console.WriteLine(A[i].ToString());
    

    Consider this Example to understand the usage of for loops and foreach loops:

    int[] test = { 9, 8, 7, 6, 5, 4 };
    
    foreach (int i in test)
        Console.WriteLine(i);
    
    Console.WriteLine();
    
    for (int i = 0; i < test.Length; i++)
        Console.WriteLine(i);
    
    Console.WriteLine();
    
    for (int i = 0; i < test.Length; i++)
        Console.WriteLine(A[i]);
    
    // Output:
    // 9
    // 8
    // 7
    // 6
    // 5
    // 4
    //
    // 0
    // 1
    // 2
    // 3
    // 4
    // 5
    //
    // 9
    // 8
    // 7
    // 6
    // 5
    // 4
    

    And also note that there is no need for .ToString() when you want to print an integer. Just write Console.WriteLine(myInteger);.