Thread: Problem with either rand() or loops....not sure

1. Problem with either rand() or loops....not sure

My aim is to print out a grid of random characters, either a G, a W or an A. Here is my code (obviously with int main() etc):

Code:
srand(time(0));

char terrain;

for (int i = 0;i < 5; i++)
{
for (int j = 0;j < 5; j++)
{
int temp = (rand() % 2) + 1;

switch (temp)
{
case 1:
terrain[i][j] = 'G';
break;
case 2:
terrain[i][i] = 'W';
break;
default:
terrain[i][j] = 'A';
break;
}
}
}

for (int i = 0;i < 5; i++)
{
cout << "\n";
for (int j = 0;j < 5; j++)
{
cout << terrain[i][j] << "\t";
}
}
But the problem is a get some characters i want, plus i get some unexpected characters, i've played with the rand() function but i cant seem to figure out what im doing wrong, some help would be appreciated, thanks  2. Surely you're not expecting any 'A's with that code?

> terrain[i][i] = 'W';
Oh, and check the subscripts here - seems a little lacking on the J front 3. int temp = (rand() % 2) + 1;

temp can only ever be 1 or 2, so I don't think you'll ever get any A's.

Could you provide a sample output? 4. ah a simple friggin typo! I only put the 'A' in there to see if it was the rand() causing my problems and generating numbers i didnt want, thanks for that new lesson learnt - proof-read code first :P

**edit** i only wanted temp to be a 1 or 2 5. To prevent undefined behaviour from a typo, you could've intialised your variable. 6. what do you mean? i initialised it in the loop 7. I mean initializing it with pre-determined values. For example, setting each char in the array equal to '_'. Then when you try filling the array with other values latter on, if you see any underscores in your output, it's likely that you haven't successfully written to those parts of the array. 8. yeah that's what the 'A' was for, if i wasnt getting the values i wanted then it would print 'A', but i see what you mean, ill remember to try that one out  Popular pages Recent additions 