{ File: prodmat2.pas }

program ProdMatrici;
{ Legge due matrici quadrate (N per N) e costruisce in una terza matrice
  il loro prodotto.  Ripete il tutto a piacere dell'utente.
}

const
  N = 3;

type
  TipoMatrice = array[1..N, 1..N] of integer;

var
  mat1, mat2, mat3 : TipoMatrice;	{ le due matrice "dato" e
                                          la matrice "risultato }
  risposta: char;		        { per verificare se l'utente vuole
                                          moltiplicare altre matrici }


  procedure LeggiMat (var m: TipoMatrice);
  var
    i, j : 1..N;
  begin
    for i := 1 to N do
    begin
      write(' riga ', i : 2, ' ');
      for j := 1 to N do
        read(m[i, j]);
    end;
    readln
  end; { LeggiMat }


  procedure StampaMat (var m: TipoMatrice);
  var
    i, j : 1..N;
  begin
    for i := 1 to N do
    begin
      for j := 1 to N do	{ stampa riga i-esima }
        write(m[i, j] : 4);
      writeln			{ a capo per la prossima riga }
    end
  end; { StampaMat }


  procedure Prodotto (a, b: TipoMatrice; var c: TipoMatrice);
  var
    i, j,	  { contatori per scandire la costruzione della matrice C }
    k	 : 1..N;  { contatore da usare nel ciclo di accumulazione che calcola i
                    vari C[i,j] }

  begin
    for i := 1 to N do
      for j := 1 to N do
        { calcolo di C[i,j];
          usiamo dirattamente C[i,j] come accumulatore per le somme parziali }
      begin
        c[i, j] := 0;		{ inizializzazione accumulatore }
        for k := 1 to N do
          c[i,j] := c[i,j] + a[i,k] * b[k,j];
      end;
  end; { Prodotto }


begin { ProdMatrici }
  writeln('inizio programma');
  writeln('vuoi moltiplicare due matrici? (s/n) ');
  repeat
    readln(risposta);
    if (risposta <> 's') and (risposta <> 'n') then
      writeln('!!! '' s '' oppure '' n '', per favore!!!');
  until (risposta = 's') or (risposta = 'n');

  while (risposta = 's') do
  begin
    writeln('lettura prima matrice');
    LeggiMat(mat1);

    writeln('lettura seconda matrice');
    LeggiMat(mat2);

    { stampe di controllo }
    writeln;
    writeln('prima matrice letta:');
    StampaMat(mat1);
    writeln;
    writeln('seconda matrice letta:');
    StampaMat(mat2);
    writeln;
    { calcolo vettore somma e sua stampa in output }
    writeln('matrice prodotto:');
    Prodotto(mat1, mat2, mat3);
    StampaMat(mat3);

    writeln('vuoi moltiplicare due matrici? (s/n) ');
    repeat
      readln(risposta);
      if (risposta <> 's') and (risposta <> 'n')
        then writeln('!!! '' s '' oppure '' n '', per favore!!!');
    until (risposta = 's') or (risposta = 'n');
  end;
  readln
end. { ProdMatrici }