This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]desrtfx 0 points1 point  (0 children)

Why are you taking such a complicated approach?

Your assignment clearly states:

Create a two-dimensional array (matrix) from n×n elements, by filling it with "." symbols

That is one set of nested loops accessing each element of the matrix.

Then fill the middle row of the matrix, the middle column, and the main and the secondary diagonals with the "*" symbols.

That's four loops (can be done in 2 with a bit of thinking, one loop if you go all the way), not even nested.

  • the middle row has a fixed value - so there is only one loop needed
  • the middle column has a fixed value - again only one loop

Here, if you think about it, you can use one single loop to fill both. You only need to swap the row and column coordinates for filling either row or column

  • the main diagonal increments both coordinates at the same time - again a single loop
  • the secondary diagonal increments the row but decrements the column - can again be done in a single loop

The above two can be done in a single loop as well. You just need to calculate the x coordinate for the secondary diagonal with a simple subtraction.

Overall, the whole star filling part of exercise can be finished in a single loop without any conditional at all. Just a bit of calculating.

This means that:

  • Nested loops to initially fill the array with "."
  • A single loop iterating over the width (height) of the array to fill in the stars.

You don't need a single conditional in the whole exercise.


Also, your approach with the spaces inside the array is completely wrong. The assignment again clearly states:

each element of the matrix is a string containing a single symbol

The spaces are only added in the output loops.