To print a two-dimensional array (matrix) in spiral order, you can follow this algorithmic approach.
-
Initialize Boundaries: Set
top,bottom,left, andrightto define the current boundaries of the matrix. - Spiral Traversal:
- Traverse from left to right across the
toprow, then incrementtop. - Traverse from the top to bottom down the
rightcolumn, then decrementright. - If there are remaining rows, traverse from right to left across the
bottomrow, then decrementbottom. - If there are remaining columns, traverse from bottom to top up the
leftcolumn, then incrementleft. - Repeat: Continue this process until all elements are printed.
This algorithm works for any size matrix and allows you to print the elements in spiral order.