replacing elements horizontally and vertically in a 2D array
the code below ask for the user's input for the 2D array size and pr开发者_高级运维ints out something like this: (say an 18x6 grid)
..................
..................
..................
..................
..................
..................
code starts here:
#include <stdio.h>
#define MAX 10
int main()
{
char grid[MAX][MAX];
int i,j,row,col;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
printf("%c ", grid[i][j]);
}
printf("\n");
}
return 0;
}
I now ask the user for a string, then ask them where to put it for example:
Please enter grid size: 18 6
Please enter word: Hello
Please enter location: 0 0
Output:
Hello.............
..................
..................
..................
..................
..................
Please enter location: 3 4
Output:
..................
..................
..................
..Hello...........
..................
..................
program just keeps going.
Any thoughts on how to modify the code for this?
PS: Vertical seems way hard, but I want to start on horizontal first to have something to work on.
#include <stdio.h>
#include <string.h>
#define MAX 10
int main()
{
char grid[MAX][MAX];
int i,j,row, col;
char word[MAX];
int row_w,col_w;
int word_len;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
printf("Please enter word: ");
scanf("%s", word);
word_len = strlen(word);
printf("Please enter location: ");
scanf("%d %d", &row_w, &col_w);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
}
}
for (j = col_w; j < col_w + word_len; j ++) {
grid[row_w][j] = word[j - col_w];
}
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%c ", grid[i][j]);
}
printf("\n");
}
return 0;
}
精彩评论