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

• 04-08-2005
Welshy
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[5][5];         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 :)
• 04-08-2005
Salem
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
• 04-08-2005
joshdick
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?
• 04-08-2005
Welshy
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
• 04-08-2005
joshdick
To prevent undefined behaviour from a typo, you could've intialised your variable.
• 04-08-2005
Welshy
what do you mean? i initialised it in the loop
• 04-08-2005
joshdick
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.
• 04-08-2005
Welshy
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 :)