program Reseni_soustavy_linearnich_rovnic_pomoci_Gaussovy_elim_metody;
uses crt;
var a : array[1..3,1..3]of real;
    b : array[1..3] of real;
    x : array[1..3] of real;
    i, j, k, m, n, o, p, r : integer;
    vymena : boolean;

procedure Vstup;
begin
  write('Vloz pocet radku soustavy linearnich rovnic : ');
  readln(n);
  writeln('Vkladej postupne hodnoty koeficientu rovnic ve tvaru :');
  writeln('                    a11 x1 + a12 x2 + ... + a1n xn = b1');
  writeln('                                    .');
  writeln('                                    .');
  writeln('                    an1 x1 + an2 x2 + ... + ann xn = bn');
  for i := 1 to n do
    for j := 1 to n+1 do
    begin
      gotoxy(8*j,i+11);
      if (j <= n) then read(a[i,j])
      else readln(b[i]);
    end;
end;

procedure Vymena_radku(c,d: integer);
var pom : real;
    e, f : integer;
begin
  if (a[c,d] = 0) then
  begin
    e := c;
    repeat
      vymena := false;
      Inc(e);
      if (a[e,d] <> 0) then
      begin
        vymena := true;
        for f := 1 to n do
        begin
          pom := a[c,f];
          a[c,f] := a[e,f];
          a[e,f] := pom;
        end;
        pom := b[c];
        b[c] := b[e];
        b[e] := pom;
      end;
    until (k = n);
  end;
end;

procedure Gauss;
var pom : real;
begin
  for i := 1 to n-1 do
    for j := i to n-1 do
      Vymena_radku(j,i);

  for i := 1 to n-1 do
  begin
    if (a[i,i] <> 0) then
    begin
      k := i;
      repeat
        Inc(k);
        if (a[k,i] <> 0) then
        begin
          pom := a[i,i]/a[k,i];
          for o := i to n do
            a[k,o] := a[k,o]*pom;
          b[k] := b[k]*pom;
        end;
          for o := i to n do
            a[k,o] := a[k,o]-a[i,o];
          b[k] := b[k]-b[i];
      until (k = n);
    end;
  end;

  if a[n,n]=0 then writeln('Chyba: Matice je singularni.')
  else begin
    x[n] := b[n]/a[n,n];
    i := n - 1;
    repeat
      pom := 0;
      for j := i + 1 to n do
	pom := pom + a[i,j]*x[j];
      x[i] := (b[i]-pom)/a[i,i];
      i := i - 1;
    until (i = 0);
  end;
end;

procedure Vystup;
begin
  for i := 1 to n do
    for j := 1 to n+1 do
    begin
      if (j <= n) then write(a[i,j]:8:2)
      else writeln(b[i]:8:2);
    end;
  writeln;
end;

procedure Vystup2;
begin
  for i := 1 to n do
    write(x[i]:8:2);
  writeln;
end;

begin
  clrscr;
  writeln('Program pro vypocet soustavy linearnich rovnic pomoci Gaussovy eliminacni');
  writeln('metody.');
  writeln;
  Vstup;
  Gauss;
  writeln;
  Vystup;
  Vystup2;
  write('Stiskni ENTER ...');
  readln;
end.