Sam Barris
Sam Barris

Reputation: 1

Pascal read int into array

I am just learning Pascal at school and have run into a weird problem in my assignment.

What I need to do is create two arrays and then read in integers for the first array until 10 numbers are read or a negative number is read, then move on to the second array with the same rules.

I have that all working fine except for the first number in the second array is always messed up. -1 seems to always be copied to array 2 index 1.

I can't give away to much code because this is an assignment but it is something like this:

while input >= 0 and index < 10 do
    begin
    read(input);
    array1[index] := input;
        index++
    end;

input:= 0; //to reset it

another while loop but for list2...

If I input for array1 1, 2, 3, -1 and array2 1, 2, 3, 4, -1 my output would be something like:

list 1: 1 list 2: -1
list 1: 2 list 2: 2
list 1: 3 list 2: 3
list 1: -1 list 2: 4

Does this make sense? I just need a little help understand why this is happening, I'm stuck here.

Upvotes: 0

Views: 4800

Answers (1)

No&#39;am Newman
No&#39;am Newman

Reputation: 6477

As comments to your question have pointed out, it's a bit difficult to find what's wrong when almost certainly the problem is with the code that you didn't post. That being said, however, there are a few visible problems

  1. Read 'input' before the 'while' loop. Entering the 'while' loop is dependent on the initial value of 'input'; I imagine that you are presuming that its initial value is 0, but it could be some garbage number with a negative value.
  2. 'index++' is not Pascal syntax, but C. This should be 'inc (index)'.
  3. Instead of writing 'input:= 0' after the first loop, this should be 'index:= 0'.

I imagine that the code, after the first 'while' loop should be

index:= 0;
readln (input);
while (input >= 0) and (index < 10) do
 begin
  inc (index);
  array2[index]:= input;
  readln (input) // there is no need for a semicolon before 'end'!
 end;

Upvotes: 1

Related Questions