A
A
alaskafx2021-12-18 11:53:46
Pascal
alaskafx, 2021-12-18 11:53:46

How to fix "Runtime Error: Index was out of array bounds"?

There is a code:

##
var num:integer;
read(num);

 var a:array of integer;
 SetLength(a, num);
 for var i:= 0 to num do begin
   Read(a[i]);
   end;


The bottom line is that the user first enters the length of the array, and then the values ​​themselves, BUT when it comes to the last element (for example 6) - I get an error like "Runtime error: Index was out of array bounds".

How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HemulGM, 2021-12-18
@HemulGM

Think with your head.
Let's say you have num = 6. And you say that there will be 6 elements in the array.
6 elements from zero are what indexes?
These are 0, 1, 2, 3, 4, 5. This is the 6 elements. You do not have an element with index 6, because it is already the 7th element, or it is best to use special functions, a universal way for all arrays , you can also not use indices at all, but iterate over all elements (but this is only for reading from an array)
for var i := 0 to num - 1 do
for var i := 0 to Pred(num) do
for var i := Low(a) to High(a) do
for var i in a do

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question