Home > Enterprise >  Does "for loop" needs to start at 0 when we are trying to assign the number to array which
Does "for loop" needs to start at 0 when we are trying to assign the number to array which

Time:03-08

I am having a issue which related to loops.

            int[] numbers= new int[5];
            for (int i = 0; i < 5; i  )
            {
                Console.WriteLine("Enter a number: ");
                numbers[i] = Convert.ToInt32(Console.ReadLine());
            }

            Array.Sort(numbers);

            foreach (int i in numbers)
            {
                Console.WriteLine(i);

            }
            Console.ReadLine();

İf i try to change the for (int i = 0; i < 5; i ) to for (int i = 1; i < 6; i ). It gives me:System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'.

What is the difference between these two?

  1. int i=0; i<5; i => 0->1->2->3->4 Length of array:5
  2. int i=1; i<6; i => 1->2->3->4->5 Length of array:5

CodePudding user response:

if your array has 5 elements the highest index is 4, as array-indices (and lists also) are zero-based.

In order to iterate all elements in an array you should therefor start at zero and stop at Length - 1. In your case that means go from zero to 4 as in your first loop.

The second loop starts at 1 and goes to 5. As 5 is not a valid index in the array (remember, it has 5 elements, but the highest index is 4), you get the exception.

Afterall you can also define for-loops from any arbitrary start-index. For example you can reverse the loop:

for(int i = array.Length - 1; i >= 0; i--) { ... }

Or you can take just the second through the fourth item:

for(int = 1; i < 4; i  ) { ... }

You can also iterate the numbers from -5 to 10, that are completely unrelated to any array:

for(int i = -5; i < 10; i  ) { ... }

So in short: a for-loop does not assume any specific start. However when iterating collections you have to ensure you stay within their bounds which are zero-based.

  • Related