Hi I am trying to create a matrix on the console using 2D array. The idea is that the output should look like this one :
1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13
Is there any one who has an idea how it can be done?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Few things you can guess from the matrix: –
First, you have to traverse all rows of a columns first before moving to the next column
Second, you need to alternate between
downwardsandupwardsdirection on each iterationSo, you would need two nested for loop, for iterating through rows for a particular column. One will go from
row 0 to max - 1, and the next will go fromrow = max - 1 to 0.Now, to alternate the iteration direction, you can use a boolean variable, and toggle it after each iteration of inner loop finishes.
Each loop needs to be enclosed inside an
if-else. Both of them will be executed on a certain condition. Ifboolean downwards = false;, then loop moving upwards will be executed and vice-versa.On each iteration, fill the current cell with an integer counter, that you would have to initialize with
1, and increment it after each fill.Pseudo code : –