Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

c++ function. for loop. How can I make the following function into a for()loop?

ID: 3556741 • Letter: C

Question

c++ function. for loop.

How can I make the following function into a for()loop? My ints ROW and COL are global constants and are equal to 3, but I want to make a function that will work no matter their values AND I want to do it in a for() loop instead of if/then statements. Any suggestions?

Here is the function:

int checkWinner(int board[ROW][COL], int &win){
win=10;
int sumR1, sumR2, sumR3, sumC1, sumC2, sumC3, sumD1, sumD2;
sumR1=board[0][0]+board[0][1]+board[0][2];
sumR2=board[1][0]+board[1][1]+board[1][2];
sumR3=board[2][0]+board[2][1]+board[2][2];
sumC1=board[0][0]+board[1][0]+board[2][0];
sumC2=board[0][1]+board[1][1]+board[2][1];
sumC3=board[0][2]+board[1][2]+board[2][2];
sumD1=board[0][0]+board[1][1]+board[2][2];
sumD2=board[2][0]+board[1][1]+board[0][2];

if (sumR1==15 || sumR2==15 || sumR3==15 || sumC1==15 || sumC2==15 || sumC3==15 || sumD1==15 || sumD2==15){
win=1;
}
if (sumR1==-15 || sumR2==-15 || sumR3==-15 || sumC1==-15 || sumC2==-15 || sumC3==-15 || sumD1==-15 || sumD2==-15){
win=2;
}
if (win==1)
cout << " Player X wins ";
if (win==2)
cout << " Player O wins ";
return win;
}

Explanation / Answer

//Hope this code snippet may help you in better understanding

int checkWinner(int board[ROW][COL], int &win){
win=10;


int sumr[3],sumc[3],sumd1,sumd2;

for(i=0;i<=2;i++){
   for(j=0;j<=2;j++){
   sumr[i]=sumr[i]+b[i][j];
   }
}
for(i=0;i<=2;i++){
   for(j=0;j<=2;j++){
   sumc[i]=sumc[i]+b[j][i];
   }
}
for(i=0;i<=2;i++){
   for(j=0;j<=2;j++){
   if(i==j){
   sumd1=sumd1+b[i][j];
   }
   }
for(i=0;i<=2;i++){
   for(j=0;j<=2;j++){
   if((i-j)==0||(i-j)==-2||(i-j)==2){
   sumd2=sumd2]+b[i][j];
   }
   }

}

if (sumr[0]==15 || sumr[1]==15 || sumr[2]==15 || sumc[0]==15 || sumc[1]==15 || sumc2[2]==15 || sumd1==15 || sumd2==15){
win=1;
}
if (sumr[0]==-15 || sumr[1]==-15 || sumr[2]==-15 || sumc[0]==-15 || sumc[1]==-15 || sumc[2]==-15 || sumd1==-15 || sumd2==-15){
win=2;
}
if (win==1)
cout << " Player X wins ";
if (win==2)
cout << " Player O wins ";
return win;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote