tags:

views:

64

answers:

1

the code below ask for the user's input for the 2D array size and prints 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.

A: 
#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;
}
Zhaojun
Please be reminded that you mixed up the "row" and "col" in the examples you provided.
Zhaojun
Also, for simplicity, I didn't do any boundary check for the "word" entered by user. But it is insecure, so you should take that into consideration when you use it in reality.
Zhaojun