0
votes

I have a problem with defining a multiple dimension

Functions ToUpper and ToLower converts capital to small.

The main function of this code is to count how many times each character appeared in an input. Only letters a-z and numbers 0-9.

VAR
    c: char;
    Counts: Array['0'..'9','a'..'z'] of Integer;
    i : Integer;
Begin
    For c := 'a' to 'z' do
        Counts[c] := 0;
    For c := '0' to '9' do 
        Counts[c] := 0;
    While not EOF do
    Begin
        Read(c);
        c := ToLower(c);
        If ( c >= 'a' ) and ( c <= 'z' ) then 
            Counts[c] := Counts[c] + 1;
        if ( c >= '0' ) and ( c <= '9' ) then
            Counts[c] := Counts[c] + 1;
    end;
    For c := 'a' to 'z' do 
        If Counts[c] <> 0 then
            WriteLn(c,Counts[c]);
end.
1

1 Answers

2
votes

If you declare Counts: Array['0'..'9','a'..'z'] of Integer; you are declaring an array of 260 elements. A multiple-index array in pascal is a multi-dimension array, that means a 2D matrix, obviously that is not what you need. You can't declare a one dimension array with more than one index, so you have to split your counters in 2 arrays. one for count numbers and the other for the letters.

The code will be:

var 
  c: char;
  numbers: Array ['0'..'9'] of Integer;
  letters: Array ['a'..'z'] of Integer;
  i : Integer; 

Begin 
  For c := 'a' to 'z' do
    letters[c] := 0;
  For c := '0' to '9' do
    numbers[c] := 0;
  While (not EOF(file)) do 
  Begin
    Read(c);
    c := ToLower(c);
    If ( c >= 'a' ) and ( c <= 'z' ) then 
      letters[c] := letters[c] + 1;
    if ( c >= '0' ) and ( c <= '9' ) then
      numbers[c] := numbers[c] + 1;
  end;
  For c := 'a' to 'z' do 
  begin
    If (letters[c] <> 0) then
      WriteLn(c,Counts[c]);
  end;
  For c := '0' to '9' do 
  begin
    If (letters[c] <> 0) then
      WriteLn(c,letters[c]);
  end;
end.

PS: Next time indent your code, and try to write a more clear question.