magic.pp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. {
  2. $Id$
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 1993-98 by Florian Klaempfl
  5. Magic Square Example
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. program magic;
  13. {
  14. Calculate a magic square (sum of the row, colums and diagonals is equal
  15. }
  16. const
  17. maxsize = 11;
  18. type
  19. sqrtype = array[1..maxsize, 1..maxsize] of longint;
  20. var
  21. square : sqrtype;
  22. size, row, sum : longint;
  23. procedure makesquare(var sq : sqrtype;limit : longint);
  24. var
  25. num,r,c : longint;
  26. begin
  27. for r:=1 to limit do
  28. for c:=1 to limit do
  29. sq[r, c] := 0;
  30. if (limit and 1)<>0 then
  31. begin
  32. r:=(limit+1) div 2;
  33. c:=limit;
  34. for num:=1 to limit*limit do
  35. begin
  36. if sq[r,c]<>0 then
  37. begin
  38. dec(r);
  39. if r<1 then
  40. inc(r,limit);
  41. dec(c,2);
  42. if c<1 then
  43. inc(c,limit);
  44. end;
  45. sq[r,c]:=num;
  46. inc(r);
  47. if r>limit then
  48. dec(r,limit);
  49. inc(c);
  50. if c>limit then
  51. dec(c,limit);
  52. end;
  53. end;
  54. end;
  55. procedure writesquare(var sq : sqrtype;limit : longint);
  56. var
  57. row,col : longint;
  58. begin
  59. for row:=1 to Limit do
  60. begin
  61. for col:=1 to (limit div 2) do
  62. write(sq[row,2*col-1]:4,' ',sq[row,2*col]:4,' ');
  63. writeln(sq[row,limit]:4);
  64. end;
  65. end;
  66. begin
  67. size:=3;
  68. while (size<=maxsize) do
  69. begin
  70. writeln('Magic Square with size ',size);
  71. writeln;
  72. makesquare(square,size);
  73. writesquare(square,size);
  74. writeln;
  75. sum:=0;
  76. for row:=1 to size do
  77. inc(sum,square[row,1]);
  78. writeln('Sum of the rows,columns and diagonals = ', sum);
  79. writeln;
  80. writeln;
  81. inc(size,2);
  82. end;
  83. end.
  84. {
  85. $Log$
  86. Revision 1.2 2002-09-07 15:06:35 peter
  87. * old logs removed and tabs fixed
  88. }