Reputation: 21
My goal is to use 2d-array to create a 50x50 "grid", and print different shapes like triangles, squares and rectangles in different locations by filling in the grid with characters like '^' and '#', something like this:
***** ^
***** ^ ^
***** ^ ^ ^
***** ^ ^ ^ ^
My current approach is by using nested for-loop to set up the grid, create boundaries and fill in the middle space with ' ':
for (r = 0; r < grid_h; r++) {
for (c = 0; c < grid_w; c++) {
grid[r][c] = ' ';
grid[r][0] = '*';
grid[r][grid_w - 1] = '*';
grid[0][c] = '*';
grid[grid_h - 1][c] = '*';
I'm not sure if the above is the fastest/correct way to create what I so called the "grid" with '*' around it (or sth like a painting area)
Anyway, my biggest problem is: What's the easiest way to fill in characters inside the grid? For example, if I want to print a square from grid[1][1] as the top left corner of the square, to grid[4][4] as the bottom right corner of the square, how should I do this in the right way? Thank you very much.
Upvotes: 2
Views: 417
Reputation: 1661
This is the most elegant way, and probably also the fastest :)
char str[3][6] = {
" ^ ",
" ^^^ ",
"^^^^^"
};
The second number has to take into account the null terminator at the end of each string. It doesn't scale well, as it requires you to fill it by hand. But the result is available for you to see right away, which is nice.
If you want to do it programmatically instead of writing it by hand like I did, you have two options:
|
for( int x = 1; x < 5; x++ ){
for( int y = 1; y < 5; y++ ){
grid[y][x] = 'R';
}
}
Upvotes: 2