# Detecting Diagonals in 2D array [C++]

Sorry i couldn’t find the category of (C++) language. But i really need help with this one, i have a college project in which i have to make tic tac toe game in =c++ with Variable board Size. So far ive done much of the stuff but i am having hard time detecting diagonals WITH IN a 2D array. This is how i detect full diagonals http://prntscr.com/fffdyh , but i need to detect them within the array. like this with size of http://prntscr.com/fffec6 .
Here is the code im using to detect full diagonals

` bool left_flag = true;
for (int i = 0, j = 0; i < SIZE; i++, j++)
if (Boards[j][i] != ‘X’)
{
left_flag = false; break;
}

``````  bool right_flag = true;
for (int i = 0, j = SIZE - 1; i < SIZE; i++, j--)
if (Boards[j][i] != 'X')
{
right_flag = false; break;
}`
``````

Help is much appriciated Thanks.

Hi @faqahat and welcome to the forums.

It looks as though the top left to bottom right check is working ok?

If there problem is the top right to bottom left diagonal check then…

…maybe try instead to check from the bottom left to the top right.

I am tapping on a tablet at the moment and hope to try your script later today,

Try this verbose script for your first test:

``````/*
# ===============================================================
# SitePoint:
https://www.sitepoint.com/community/t/detecting-diagonals-in-2d-array-c/265418

# COMPILE
gcc -o executable-2-delete  tic-tac-toe.c

# RUN
./executable-2-delete

// http://prntscr.com/fffdyh
// http://prntscr.com/fffec6
# ===============================================================
*/

#include <stdio.h>
#include <string.h>

#define SIZE 6
int iPassed, flag = 0;
char Boards[6][6] =
{
{'X', 'b', 'c', 'd', 'e', 'f'},
{'g', 'X', 'i', 'j', 'k', 'l'},
{'m', 'n', '?', 'p', 'q', 'r'},
{'s', 't', 'u', 'X', 'w', 'x'},
{'y', 'z', '1', '2', 'X', '4'},
{'5', '6', '7', '8', '9', 'X'}
};

//=====================
int main(int argc, char* argv[])
{
printf("\n ================================");
printf("\n Testing top-left to bottom-right");
printf("\n ================================");

// ASSUME PASSED
iPassed = 1;

// LOOP THROUGH ALL ITEMS
for (int row=0, col=0; row < SIZE; row++, col++)
{
printf("\n\t %d %d ==> %c", row, col, Boards[row][col]);

// TEST FOR SINGLE FAILURE
if ( Boards[row][col] != 'X' )
{
// FAILED
iPassed = 0;
printf("\t :( FAILED");
// break;
}
}//endfor

// RESULT
printf("\nRESULT:\t");
if( iPassed )
{
printf("PASSED");
}else{
printf("FAILED");
}//endif
printf("\n\n");

}//endmain ====================================

``````

Output:

`````` ================================
Testing top-left to bottom-right
================================
0 0 ==> X
1 1 ==> X
2 2 ==> ?	 :( FAILED
3 3 ==> X
4 4 ==> X
5 5 ==> X
RESULT:	FAILED

``````

#### I would not like to give you a full solution to the second test but will mention it was a little more difficult

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.