/* Fill a square matrix with the values 0 to N**2-1, */ /* in a zig-zag fashion. */ /* N is the length of one side of the square. */ /* Written 22 February 2010. */ declare n fixed binary; put skip list ('Please type the size of the matrix:'); get list (n); begin; declare A(n,n) fixed binary; declare (i, j, inc, q) fixed binary; on subrg snap begin; declare i fixed binary; do i = 1 to n; put skip edit (a(i,*)) (f(4)); end; stop; end; A = -1; inc = -1; i, j = 1; loop: do q = 0 to n**2-1; a(i,j) = q; if q = n**2-1 then leave; if i = 1 & j = n then if iand(j,1) = 1 then /* odd-sided matrix */ do; i = i + 1; inc = -inc; iterate loop; end; else /* an even-sided matrix */ do; i = i + inc; j = j - inc; iterate loop; end; if inc = -1 then if i+inc < 1 then do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end; if inc = 1 then if i+inc > n then do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end; if inc = 1 then if j-inc < 1 then do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end; if inc = -1 then if j - inc > n then do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end; i = i + inc; j = j - inc; end; /* Display the square. */ do i = 1 to n; put skip edit (a(i,*)) (f(4)); end; end;