Help with Arrays

Hello guys,

i need help with some arrays. So first of all i have global arrays, for example

 
  Square[9] = {'1', '2', // and like that 


then i have a function that i call every time i need to reset the arrays. Instead of doings this

1
2
Square[0] = '1';
Square[1] = '2';


how can i set them all back?

2nd question

how can i use an array (for example from 1 to 9) in an if statement?
You can reset them with a loop like so:
1
2
3
for (int i = 0; i < 9; i++) {
   Square[i] = i + 1;
}


You can frame conditionals with the indexes of an array:
if (Square[0] == Square[1] && Square[1] == Square[2]) { ... }
how can i set them all back?

Easiest way to set them back is a probably simple for loop:
1
2
3
 
    for (int i=0; i<9; i++)
        Square[i] = i + '0';  // Add the value of ASCII zero to the index 


how can i use an array (for example from 1 to 9) in an if statement?

Just use a subscript as you did in your assignment statements. Keep in mind that if you're representing the grid as 1-9 to the user, your subscripts are from 0-8.
1
2
3
  if (Square[4] == 'X')     //  Check the middle square
  {  // then do something
  }

Note: You didn't show the type of Square. I'm assuming it's char.

Last edited on
Isnt it possible to make it shorter in an if statement for an array from 1 to 9 and not writing every single one?

also i use char Square[9] so it does not work with what you said, how can i fix it?
Last edited on
Yes you can again use a loop.
1
2
3
4
for (int i = 0; i < 9; i++) {
   if (Square[i] == 'X') 
      // do something
}

That's an example, if you want something more specific you need to tell us exactly what you're trying to do.

And what do you mean it didn't work? Can you post the entire code and explain what wasn't working?
to reset square, consider...
const char orig[9] = {'1','2','3'}; //you can fill in the rest of them yourself.
...
char square[9];
memcpy(square, orig, 9); //9 = sizeof(char) * # of items, 9*1 = 9
to reset it.

you could also make orig a c-string or string. if they were all strings, a simple = assignment operator would do all the work for you:
const string orig = "123456789";
string square = orig;
...
//reset with
square = orig; // good times
you can still access orig as if it were a char array:
orig[x] works just fine!

Last edited on
Topic archived. No new replies allowed.