Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does "for loop" needs to start at 0 when we are trying to assign the number to array which we get it from user?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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

>Solution :

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--) { ... }

You can also iterate the numbers from 5 to 10:

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 iterate within their bounds which are zero-based.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading