JavaScript nested for loops
3 views (last 30 days)
Show older comments
I am new to coding. I need to create a code that prints a coordinate plane from (0,0) to (9,9). I then need to delete certain cells to make a diagonal line through the plane.
Answers (1)
Arjun
on 6 Dec 2024
I understand that you want to create a grid of co-ordinate points from (0,0) to (9,9) and then delete the diagonal elements to obtain the final grid.
In order to create a grid with co-ordinate points, since the grid is a 2-D grid you have to run 2 nested "for" loops or "while" loops to populate the grid entirely with the co-ordinate points and then after you have obtained this grid, again run a "for" loop to delete the elements on the primary and secondary diagonals. To identify primary and secondary diagonal elements use the following equations:
- Primary Diagonal: Elements with co-ordinates (i,i)
- Secondary Diagonal : Elements with co-ordinates (i,gridSize-i+1)
Note: "i" is the loop control variable.
Kindly refer to the code below for better understanding:
gridSize = 10;
% Initialize the grid with coordinate tuples
grid = strings(gridSize, gridSize);
% Fill the grid with coordinate tuples
for x = 1:gridSize
for y = 1:gridSize
% MATLAB uses 1-based indexing, adjust to 0-based
grid(x, y) = sprintf('(%d,%d)', x-1, y-1);
end
end
% Remove cells to create both diagonals
for i = 1:gridSize
grid(i, i) = " "; % Main diagonal
grid(i, gridSize - i + 1) = " "; % Secondary diagonal
end
% Display the modified grid
disp('Grid with Both Diagonals Removed:');
for i = 1:gridSize
disp(grid(i, :));
end
Kindly refer to the documentation of "for" loops for better understanding: https://www.mathworks.com/help/releases/R2021a/matlab/ref/for.html
I hope this will help!
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!