Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have a code that sorts an array in ascending order, I'm trying to display every 10th number from that array. However I keep getting an error:
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

Could anyone please explain why it appears and how I could fix it?
Thanks

What I have tried:

The error appears at:
C#
Console.Write(arr[i * 10] + " ");


The Code:
C#
{
                string[] text = File.ReadAllLines("Net_1_256\\Net_1_256.txt");
                List<int> values = new List<int>(text.Length);
                int i;
                foreach (string line in text)
                    {
                    int value;
                    if (int.TryParse(line,out value))
                        {
                            values.Add(value);
                        }
                }

                int[] arr = values.ToArray();
                for (i = 0; i < arr.Length; ++i)
                HeapSort(arr, arr.Length);

                Console.Write("\nSorted Array is: ");
                for (i = 0; i < arr.Length; ++i)
                {
                    Console.Write(arr[i * 10] + " ");
                }
            }
Posted
Updated 12-Mar-20 10:14am
Comments
Benktesh Sharma 12-Mar-20 16:11pm    
Did you intend to print every 10th including the first or excluding the first?

Think about it - your variable i will run through every valid index within the array, so i * 10 is going to be an invalid index most of the time.

If the valid indices are 0 to 4, you're trying to display the items at 0, 10, 20, 30, and 40. Only the first one will succeed.

To display every 10th item in the array, change your loop to increment by 10 instead of 1:
C#
for (i = 0; i < arr.Length; i += 10)
{
    Console.Write(arr[i] + " ");
}

NB: As per a discussion in the Lounge[^], there is potentially some confusion over your requirements. The code in your question suggests that you want to start with the first element of the array. But "every 10th element" could be interpreted to mean that you start with the tenth element of the array.

If you want to start with the 10th element in the array, then you simply need to change the starting position of the loop:
C#
for (i = 9; i < arr.Length; i += 10)
 
Share this answer
 
v2
Comments
Maciej Los 13-Mar-20 7:22am    
Up-voted!
When you are writing the 10th element, the number may be out of the range. For example, if you have 2 elements in the array, you are trying to access the element at 2 * 10 which does not exist. You can solve this either by putting a condition in the for loop where i * 10 < arr.Length (example shown). Another way is to i < arr.Length/10 (so that i*10 is always within the bound). The code below assumes that the requirement is that the first element and every 10th after first be printed.

{
                string[] text = File.ReadAllLines("Net_1_256\\Net_1_256.txt");
                List<int> values = new List<int>(text.Length);
                int i;
                foreach (string line in text)
                    {
                    int value;
                    if (int.TryParse(line,out value))
                        {
                            values.Add(value);
                        }
                }

                int[] arr = values.ToArray();
                for (i = 0; i < arr.Length; ++i)
                HeapSort(arr, arr.Length);

                Console.Write("\nSorted Array is: ");
                for (i = 0; i < arr.Length && i*10 < arr.Length; ++i)
                {
                    Console.Write(arr[i * 10] + " ");
                }
            }
 
Share this answer
 
v2
Comments
Nelek 12-Mar-20 4:03am    
This prints element [0] and that is no 10th element. An additional if is needed in the last for
Benktesh Sharma 12-Mar-20 7:03am    
@Nelek, the loop is printing the actual number in the array. The original code from the poster of the question intended to print 1st, 10th and so on. In addition, 'every 10th' implies first, tenth, twentieth and so one. You may be right in handling other edge conditions, but the original concern was 'index out of bound exception'.
Nelek 12-Mar-20 8:28am    
Ok... than is probably a language problem.
For me every 10th doesn't necessarily imply the first one. I would have done [9], [19],... (cardinals 10, 20, 30...) and so on instead of [0], [10] (cardinals 1, 11, 21,...)
Benktesh Sharma 12-Mar-20 8:51am    
I see. Thanks.
Rick York 12-Mar-20 16:04pm    
This solution is incorrect. When i is 0 it prints item 0 and that IS NOT the tenth element. It is the zeroth element, if that is even a word.
if i * 10 > arr.Length than you will get that error.

Rule of thumb is a bit to not manipulate your index inside the loop:
so


C#
for (i = 0; i < arr.Length; i++)
{
    //here you actually manipulate the index
    Console.Write(arr[i*10] + " ");
}

is not such a good idea.

to avoid errors in the future a check can be added
if(i * 10 < arr.Length) { /*do something here*/ }

or better, rethink your loop :
eg. add if(i%10 == 0){ /*write out what you need*/ }

hope this helps.
This should be in your textbooks or solved with your classmates though...
 
Share this answer
 
v2
Comments
Nelek 11-Mar-20 10:23am    
Your or better "if" would print the very first number of the array (Pos[0]) and it is not in the requirement.
If you want to do it like this, an additional if clause is needed:
if((i%10 == 0)&&(i!=0)){ /*write out what you need*/ }

and that would work better if the loop just uses i++ instead of i+=10 as you wrote
V. 12-Mar-20 3:24am    
that was a typ-o ;-)
Corrected
Richard Deeming 11-Mar-20 10:45am    
Minor correction: you'll get the error if i * 10 >= arr.Length. :)
Rick York 12-Mar-20 16:03pm    
This solution is incorrect. When i is 0 it prints item 0 and that IS NOT the tenth element.
PIEBALDconsult 13-Mar-20 12:01pm    
Yet it may be what the OP intended, but was unclear in how he described it.
Quote:
However I keep getting an error

It is not a direct solution, but the debugger is a tool to help you understand what is going on in your code.
-----
Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

Debugging C# Code in Visual Studio - YouTube[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
v2
Comments
[no name] 12-Mar-20 15:55pm    
"It is not a direct solution", it is not even an indirect one. Sorry for me thing like this looks like rep hunting.
Btw. no vote from my side
Patrice T 12-Mar-20 16:28pm    
Hi, thanks for the comment.
First of all, I didn't wanted to just repeat what was said in the 3 previous solution.
My experience, dating from before internet, is that the debugger is always a great help to understand what my code is doing wrong.
Unfortunately, it seems that the debugger is not in great fashion today and that beginners are often learning to code without being taught the debugger.
The tenth element in a array is item 9 since the first one is item 0. Every tenth element would be items 9, 19, 29, 39, etc. You could try something like this :
C
for( index = 9; index < arr.length; index += 10 )
{
    Console.Write( arr[index] + " " );
}
If the array has less than 10 elements nothing would be printed, nor should there be.
 
Share this answer
 
Comments
Richard Deeming 13-Mar-20 7:17am    
So you down-voted my solution whilst I was asleep because a discussion in the Lounge - which you didn't even participate in - decided that "every 10th item" meant starting at a different index.

Then posted what is essentially a copy of the code from my solution (with the variable name changed so that it wouldn't compile if the OP tried to use it), changing the start of the loop.

Not cool. 👎
Rick York 15-Mar-20 3:14am    
Not cool??? What I wrote was written BEFORE your edit.
Richard Deeming 16-Mar-20 5:39am    
Re-read my comment.

Note that I said "... essentially a copy of ...". The code block is too trivial to assume that you actually copied it. I was merely pointing out the similarities. If you hadn't renamed the variable, your code would be a single character change from mine.

My solution was posted long before yours. You obviously saw it because you commented on it - you've since deleted that comment, but deleted comments are still visible.

Down-voting my solution because I didn't edit it to account for a discussion that happened whilst I was asleep is definitely "not cool".
Stefan_Lang 13-Mar-20 8:35am    
This may be a problem of language, but when you say 'item 9' I understand 'the element arr[8]'. There is no such thing as 'item 0' in my understanding: the first element in a set is always item 1.

I'm not sure whether a native english speaker would understand it differently.
Rick York 15-Mar-20 3:21am    
When I wrote item 9 I meant arr[9].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900