Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Print All Elements of Two Dimensional Array in Spiral

Objec­tive: This ques­tion was asked in Ama­zon inter­view for the Soft­ware devel­op­ment Engi­neer posi­tion, Write an algo­rithm to print all the ele­ments of two dimen­sional array in spi­ral.
Exam­ple :

Print 2D array in Spiral

Print 2D array in Spiral

Input: Two dimen­sional array

Out­put: All array ele­ments printed in spiral.

Approach:

  • Start print­ing from first row.
  • Print row and columns, for­ward and back­ward alternatively
  • With every iter­a­tion of (either row or col­umn), reduce the size of an row or col­umn by 1
  • Call recur­sively

Com­plete Code:

Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

You may also like...

  • Hari Kiran

    Awe­some tuto­ri­als. Please make more. I am a huge fan of your tutorials .

    • Sumit Jain

      Thanks Hari, Your com­ment is moti­va­tion for me 🙂

  • Nis­hant Dehariya

    really awe­some i find every­thing easy and bet­ter than geeks­forgeeks although i m c++ guy.