Search code examples
pascalfreepascalmagic-square

Magic Square FreePascal


Program must output whether the square is magic square or not.

I must read square from file.

Magic square - all rows, all columns and both diagonals sum must be equal.

Program shows right answer, but these 16 numbers must be read from text file.

Text file is looking like:

1 1 1 1
2 2 2 2 
3 3 3 3
4 4 4 4

Program itself:

var
  m:array[1..4,1..4] of integer;
  i:byte;
  j:byte;
  r1,r2,r3,r4,c1,c2,c3,c4,d1,d2:integer;

begin

for i:=1 to 4 do
  for j:=1 to 4 do

  begin
    write('Enter value for column=',i,' row=',j,'  :');
    readln(m[i,j]);
  end;

r1:=m[1,1]+m[1,2]+m[1,3]+m[1,4];
r2:=m[2,1]+m[2,2]+m[2,3]+m[2,4];
r3:=m[3,1]+m[3,2]+m[3,3]+m[3,4];
r4:=m[4,1]+m[4,2]+m[4,3]+m[4,4];
c1:=m[1,1]+m[2,1]+m[3,1]+m[4,1];
c2:=m[1,2]+m[2,2]+m[3,2]+m[4,2];
c3:=m[1,3]+m[2,3]+m[3,3]+m[4,3];
c4:=m[1,4]+m[2,4]+m[3,4]+m[4,4];
d1:=m[1,1]+m[2,2]+m[3,3]+m[4,4];
d2:=m[1,4]+m[2,3]+m[3,2]+m[4,1];

if (r1=r2) and (r2=r3) and (r3=r4) and (r4=c1) and (c1=c2) and (c2=c3) and (c3=c4) and (c4=d1) and (d1=d2) then
  begin
  write('Magic Square');
  end

else
  begin
  write('Not Magic Square');
  end;

readln;

end.

Solution

  • Here is a procedure to read the matrix from a text file. The row elements are supposed to be separated with space.

    type
      TMatrix = array[1..4,1..4] of integer;
    
    procedure ReadMatrix( const filename: String; var M: TMatrix);
    var
      i,j : integer;
      aFile,aLine : TStringList;
    begin
      aFile := TStringList.Create;
      aLine := TStringList.Create;
      aLine.Delimiter := ' ';
      try
        aFile.LoadFromFile(filename);
        Assert(aFile.Count = 4,'Not 4 rows in TMatrix');
        for i := 0 to 3 do
        begin
          aLine.DelimitedText := aFile[i];
          Assert(aLine.Count = 4,'Not 4 columns in TMatrix');
          for j := 0 to 3 do
            M[i+1,j+1] := StrToInt(aLine[j]);
        end;
      finally
        aLine.Free;
        aFile.Free; 
      end;
    end;