-
Help with a grid
Hello,
I am completely new to C programming so this may be a very trivial question but i cannot do it. I have to make a simple grid wich displays dots. The tricky part is that the user enters a width and a height and then the grid is generated and printed with that width and height. This grid needs to be stored in an array as well.
I believe im overcomplicating the problem but this is what i have so far:
Code:
# include <stdio.h>
int lx;
int ly;
char grid [10] [10];
int i;
int j;
int main()
{
printf ("Insert the width (Lx) and height (Ly) of the grid \n");
scanf ("%d %d", &lx, &ly);
for (i = 0; i < lx; i++)
{
for (j=0; j < ly; j++)
{
grid [i] [j] = ".";
}
}
for (i = 0; i < lx; i++)
{
for (j=0; j < ly; j++)
{
printf ("%c", grid [i] [j]);
}
}
}
The output that im getting is a line of i's rather than a grid. i need these to be dots in a 2d grid.... how do i go about this?
Thanks in advance.
-
First question... what happens if your user types 20 x 30 for the grid size?
"." asks your grid elements to be strings... you should use the single quote (apostropic) version... '.' for assigning your values.
In your final loop while printing, you need to put a newline inside the outer loop but not inside the inner loop... printf("\n\"); should work.
-
You need to print a new line after every row.
-
hmmm ok. Ive put a new line in the loop but now its outputing the same thing but in a long column... how do i input the lines to be just after every row?
-
Code:
for (i = 0; i < lx; i++)
{
for (j=0; j < ly; j++)
{
printf ("%c", grid [i] [j]);
}
printf("\n"); /* <-- goes here, the completion of the row loop */
}
-
As Tater said, inside your outer loop [the for (i = 0...)], but outside your inner loop [the for (j = 0...)].
-
o great thanks you all so much it works fine now :)