Practice Program
Creating, Printing, and Processing Through a 2-D Array (Matrix)

;;; Set up the input array:
(defparameter *nrows* 8)
(defparameter *ncols* 8)

(defparameter *test-array*
  (make-array (list *nrows* *ncols*) :initial-contents
  '((0 1 0 8 0 9 0 0)
    (0 2 3 0 0 0 0 0)
    (0 0 0 1 0 0 0 0)
    (0 0 0 0 6 4 7 0)
    (0 0 0 0 3 0 7 0)
    (8 8 8 0 1 2 7 0)
    (0 9 9 0 0 0 0 0)
    (0 0 0 0 0 0 0 0) 
   ) 
  )
)

;;Printing a 2-D array 
(defun print-image (image)
  "Prints out IMAGE nicely formatted."
  (dotimes (row *nrows*)
    (dotimes (col *nrows*)
      (format t "~5D" (aref image row col))
    )
    (format t "~%")   ;; or (terpri) also generates a new line
  ) 
)

(defun sqr (x)
  "Returns X squared."
  (* x x)
)

;;Go through each element in the matrix, counting and squaring
(defun scan-sqr (image)
  "Performs a raster-scan of the image and
   counts and squares successive elements."
  (let ((count 0)
        (image2 (make-array (list *nrows* *ncols*)))
       )
    (dotimes (row *nrows*)
      (dotimes (col *ncols*)
        (incf count)
        (format t "Scanning ~s, ~s, count=~s.~%" 
                                     row col count) ; Show progress.
        (setf (aref image2 row col) (sqr (aref image row col)))
      )
    )
    image2
   ) 
)

;;This is like function main() in a C program
(defun test ()
  "Performs a demonstration."
  (format t "Initial matrix:~%")
  (print-image *test-array*)
  (format t "~%Each element squared:~%")
  (print-image (scan-sqr *test-array*) ) 
  (format t "~%")  ;; or use (terpri) for a new line
)

(test)    ;;This command runs the program when you load it