I have written code for many patterns but unable to write for this….. not even getting any hint how to proceed.
I want to generate the following output:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
…where the width and height of the rectangle are specified as inputs.
I would do it this way:
Initialize a 5×5 two-dimensional array of integers to 0. Have a
directionvariable, and define constants or anenumfor the four directions. Start moving ‘right’ from (0, 0), filling in the array with increasing values until you hit the edge or a number that is not 0. Then, increment the direction (and wrap) and continue. Then print the array in rows.An alternative using loops is to iterate over all the (x, y) coordinates, and pass x and y into a function that gives you the value at that position. The function I wrote does exactly the same thing as would the function that fills the array, except it doesn’t write to an array, and when it reaches the given (x, y) it returns the current value. Not very efficient, but it achieves the result.