Received an "expected expression error " when i added a function - c

Im trying to write a program that wont compile. The error i keep receiving reads like this
expected expression
destroyFallingStone (int map[][SIZE], int column);
It happened after i added the destroyFallingStone function and Ive checked the function and function prototype for any syntax errors. I don't know where Ive made a mistake.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define SIZE 15
#define EMPTY 0
#define STONE 1
// TODO: Add any extra #defines here.
// TODO: Add any extra function prototypes here.
void printMap(int map[SIZE][SIZE], int playerX);
void destroyFallingStone (int map[][SIZE], int column);
int main (void) {
// This line creates our 2D array called "map" and sets all
// of the blocks in the map to EMPTY.
int map[SIZE][SIZE] = {EMPTY};
// This line creates out playerX variable. The player starts in the
// middle of the map, at position 7.
int playerX = SIZE / 2;
printf("How many lines of stone? ");
// TODO: Scan in the number of lines of blocks.
int linesOfStone;
scanf("%d", &linesOfStone);
printf("Enter lines of stone:\n");
// TODO: Scan in the lines of blocks.
int rowPos;
int columnPos;
int stoneLength;
int stoneValue;
int i = 0;
while (i < linesOfStone) {
scanf("%d %d %d %d", &rowPos, &columnPos, &stoneLength, &stoneValue);
if ( 0 <= rowPos && rowPos < SIZE &&
0 <= columnPos && columnPos < SIZE
&& columnPos + stoneLength - 1 < SIZE) {
int j = 0;
while (j < stoneLength) {
map[rowPos][columnPos + j] = STONE;
j++;
}
}
i++;
}
printMap(map, playerX);
// TODO: Scan in commands until EOF.
// After each command is processed, you should call printMap.
int quitLoop = 0;
int playerDirection = 0;
int playerMovement = 0;
while (quitLoop != 1) {
scanf("%d %d", &playerMovement, &playerDirection);
if ( playerMovement == 1 &&
playerDirection == 1 && playerX < (SIZE - 1)) {
//check player is within bounds
playerX++;
} else if ( playerMovement == 1 &&
playerDirection == -1 && playerX > 0 ) {
playerX--;
} else if ( playerMovement == 2) { // call function for destroying stones
destroyFallingStone (int map[][SIZE], int column);
}
printMap(map, playerX);
}
return 0;
}
// Print out the contents of the map array. Then print out the player line
// which will depends on the playerX variable.
void printMap(int map[SIZE][SIZE], int playerX) {
// Print values from the map array.
int i = 0;
while (i < SIZE) {
int j = 0;
while (j < SIZE) {
printf("%d ", map[i][j]);
j++;
}
printf("\n");
i++;
}
// Print the player line.
i = 0;
while (i < playerX) {
printf(" ");
i++;
}
printf("P\n");
}
//destroys the closes 2 stones
void destroyFallingStone (int map[][SIZE], int column) {
int i = 0;
int j = 0;
while (j < 3) {
while (i < 15 && map[i][column] != STONE) { //finding the first stone
i++;
}
// if there is a stone, destroy it
if (map[i][column] == STONE) {
map[i][column] = EMPTY;
}
i++;
}
}

You're not calling the function correctly:
} else if ( playerMovement == 2) { // call function for destroying stones
destroyFallingStone (int map[][SIZE], int column);
}
What you have here looks more like a declaration than a function call. You instead want:
} else if ( playerMovement == 2) { // call function for destroying stones
destroyFallingStone(map,column);
}

The problem is in line: 75 destroyFallingStone (int map[][SIZE], int column);. This should be a call to function destroyFallingStone. Something like destroyFallingStone (map, columnPos);.
Following is corrected code. See it compiling here:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define SIZE 15
#define EMPTY 0
#define STONE 1
// TODO: Add any extra #defines here.
// TODO: Add any extra function prototypes here.
void printMap(int map[SIZE][SIZE], int playerX);
void destroyFallingStone (int map[][SIZE], int column);
int main (void) {
// This line creates our 2D array called "map" and sets all
// of the blocks in the map to EMPTY.
int map[SIZE][SIZE] = {EMPTY};
// This line creates out playerX variable. The player starts in the
// middle of the map, at position 7.
int playerX = SIZE / 2;
printf("How many lines of stone? ");
// TODO: Scan in the number of lines of blocks.
int linesOfStone;
scanf("%d", &linesOfStone);
printf("Enter lines of stone:\n");
// TODO: Scan in the lines of blocks.
int rowPos;
int columnPos;
int stoneLength;
int stoneValue;
int i = 0;
while (i < linesOfStone) {
scanf("%d %d %d %d", &rowPos, &columnPos, &stoneLength, &stoneValue);
if ( 0 <= rowPos && rowPos < SIZE &&
0 <= columnPos && columnPos < SIZE
&& columnPos + stoneLength - 1 < SIZE) {
int j = 0;
while (j < stoneLength) {
map[rowPos][columnPos + j] = STONE;
j++;
}
}
i++;
}
printMap(map, playerX);
// TODO: Scan in commands until EOF.
// After each command is processed, you should call printMap.
int quitLoop = 0;
int playerDirection = 0;
int playerMovement = 0;
while (quitLoop != 1) {
scanf("%d %d", &playerMovement, &playerDirection);
if ( playerMovement == 1 &&
playerDirection == 1 && playerX < (SIZE - 1)) {
//check player is within bounds
playerX++;
} else if ( playerMovement == 1 &&
playerDirection == -1 && playerX > 0 ) {
playerX--;
} else if ( playerMovement == 2) { // call function for destroying stones
destroyFallingStone (map, columnPos);
}
printMap(map, playerX);
}
return 0;
}
// Print out the contents of the map array. Then print out the player line
// which will depends on the playerX variable.
void printMap(int map[SIZE][SIZE], int playerX) {
// Print values from the map array.
int i = 0;
while (i < SIZE) {
int j = 0;
while (j < SIZE) {
printf("%d ", map[i][j]);
j++;
}
printf("\n");
i++;
}
// Print the player line.
i = 0;
while (i < playerX) {
printf(" ");
i++;
}
printf("P\n");
}
//destroys the closes 2 stones
void destroyFallingStone (int map[][SIZE], int column) {
int i = 0;
int j = 0;
while (j < 3) {
while (i < 15 && map[i][column] != STONE) { //finding the first stone
i++;
}
// if there is a stone, destroy it
if (map[i][column] == STONE) {
map[i][column] = EMPTY;
}
i++;
}
}

Related

i'm having some problem with saveing the vaule of the longest fence

I'm having some problem with saveing the vaule of the longest fence.
I tried this:
int longestFence(char input [], int size)
{
int i , max = 0, count = 0;
for(i = 0; i < size ; i++)
{
if(input[i] == '|' && input[i] == '-')
{
count = 1;
}
if(input[i] != input[i + 1])
{
count++ - 1;
}
}
return count;
}
In practice, to detect is the fence is still valid, you just have to check if the current symbol is different or not than the previous one.
You also have to check if the current count is longer or not than the previous longest one.
Besides, I modified the random string generator: the current one is rather inefficient.
In addition, the string generated is not terminated by the Null character. I also modified it.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
int longestFence (char input[], int size) {
if (size == 0) return 0;
int max_count = 0;
int count = 1;
for (int i = 1; i < size; ++i) {
if (input[i] != input[i-1]) {
count++;
} else {
if (count > max_count) max_count = count;
count = 1;
}
}
if (count > max_count) max_count = count;
return max_count;
}
int main() {
char string[MAX+1];
char symbols[] = {'|', '-'};
srand (time(NULL));
int length = rand() % (MAX+1);
for (int i = 0; i < length; ++i) {
int val = (rand() / 16) % 2;
string[i] = symbols[val];
}
string[length] = '\0';
printf ("String is: %s\n", string);
printf ("Longest fence = %d\n", longestFence (string, length));
return 0;
}

Print all combination of a string using recursion in C

I have an assignment to write code that printing all combinations of N char. For example, if the input is 3, the expected output must be "aaa aab aac aba ... ccc". But my code looping over and over again. Here's my code.
#include <stdio.h>
#ifndef MAX
#define MAX 5
#endif
void comb(char kar[], int size, int index) {
// string = aaa
// lim = 'd'
char lim = 'a' + size;
while (index != -1) {
if (kar[size-1] != lim) { // != c
for (int i = 0; i < size; i++) {
printf("%s ", kar);
kar[size-1]+=1;
}
return comb(kar, size, index);
} else {
while (kar[index-1] == lim && index != -1) {
kar[index-1]='a';
index--;
}
kar[index-1] += 1;
return comb(kar, size, size);
}
}
}
int main(int argc, char const *argv[]) {
int n;
char kar[MAX];
printf("Input N char : ");
scanf(" %d", &n);
for (int j = 0; j < n; j++) {
kar[j] = 'a';
}
comb(kar, n, n);
return 0;
}
I'm a little bit confused and I have no idea where is the mistake. Thank you.
The problem has been solved. I changed some elements in the comb() and added the pow() function to define the recursion limit.
int comb(char kar[], int size, int index, int limit) {
char lim = 97 + size;
int limit_value = pow(size,size);
if(limit == limit_value){
return 1;
} else {
if (index < size-1) {
printf("%s ", kar);
kar[size-1]+=1;
return comb(kar, size, index+1, limit+1);
} else {
int cek = index;
printf("%s ", kar);
while (kar[cek] == lim-1 ) {
kar[cek]=97;
cek-=1;
}
kar[cek] += 1;
return comb(kar, size, 0, limit+1);
}
}
}

Two-Way Insertion Sort not sorting

This is supposed to be a Two-Way insertion sort, but it's not sorting. I'm also supposed to print out the number of assignments for sorting, but right now I just want it to sort.
A separate output array of size 2n+1 is set aside. Initially x[0] is placed into the middle element of the array n.
Continue inserting elements until you need to insert between a pair of elements in the array.
As before you need to make room for the new element by shifting elements. Unlike before,
you can choose to shift all smaller elements one step to the left or all larger elements one step
to the right since there is additional room on both sides of the array. The choice of which
shift to perform depends on which would require shifting the smallest amount of elements.
I can't find much on the internet about this sort except that no one uses it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printArray(int arr[], int len) {
for (int j = 0; j < len; j++)
printf("%d ", arr[j]);
printf("\n");
}
int main() {
FILE *in;
int size_arr = 0;
char ch;
if ((in = fopen("data_a5.txt", "r")) == NULL) {
printf("Error!");
exit(1);
}
do {
ch = fgetc(in);
if (ch == '\n')
size_arr++;
} while (ch != EOF);
rewind(in);
int arr[size_arr];
int sort_arr[2 * size_arr + 1];
int n = 0;
while (!feof(in)) {
fscanf(in, "%d", &arr[n]);
n++;
}
fclose(in);
for (n = 0; n < 2 * size_arr; n++) {
sort_arr[n] = 0;
}
sort_arr[size_arr] = arr[0];
for (n = 1; n < size_arr; n++) {
int index = size_arr;
if (arr[n] <= sort_arr[size_arr]) {
while (!(arr[n] <= sort_arr[index]) && sort_arr[index] != 0 && index >= 0) {
index--;
}
}
if (arr[n] > sort_arr[size_arr]) {
while (!(arr[n] <= sort_arr[index]) && sort_arr[index] != 0 && index < 2 * size_arr) {
index++;
}
}
if (sort_arr[index] == 0) {
sort_arr[index] = arr[n];
} else {
int next_R, next_L = index;
while (sort_arr[next_R] != 0 && next_R <= 2 * size_arr) {
next_R++;
}
while (sort_arr[next_L] != 0 && next_L >= 0) {
next_L--;
}
int R_move = next_R - index;
int L_move = index - next_L;
if (R_move > L_move) {
while (L_move <= index) {
sort_arr[L_move] = sort_arr[L_move + 1];
L_move++;
}
sort_arr[index] = arr[n];
} else {
while (R_move >= index) {
sort_arr[R_move] = sort_arr[R_move - 1];
R_move--;
}
sort_arr[index] = arr[n];
}
}
}
printArray(arr, size_arr);
return 0;
}
I'm not sure this solves all problems but it is a problem you must fix.
This code
int next_R, next_L = index;
while(sort_arr[next_R] != 0 && next_R <= 2*size_arr)
has undefined behavior as next_R is uninitialized.
Maybe you want:
int next_R = index, next_L = index;
^^^^^
while(sort_arr[next_R] != 0 && next_R <= 2*size_arr)
In any case you have to initialize next_R before using it.
I also find this line strange:
printArray(arr, size_arr);
^^^
Seems you are printing the original array instead of the sorted array.
May be you want:
printArray(sort_arr, size_arr);
^^^^^
There are some problems in your code:
when you scan the file in the first pass, you should count the number of integers instead of the number of characters.
when inserting, your loops are off by one: the tests should read while (L_move < index) and while (R_move >= index)
while (!feof(in)) is always wrong, you should instead write while (fscanf(in, "%d", &arr[n]) == 1) {...
you should probably allocate the arrays arr and sort_arr instead of defining them as VLAs with automatic storage to prevent undefined behavior on large input files.
you should use binary search into the sorted portion, otherwise your algorithm has a basic complexity of O(N2) that dwarfs the small gain obtained from the minimisation of the insertion phase.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
void print_array(const int arr[], int len) {
for (int j = 0; j < len; j++)
printf("%d%c", arr[j], " \n"[j == len - 1]);
}
int main(void) {
FILE *in;
int size_arr, n, start;
int value;
if ((in = fopen("data_a5.txt", "r")) == NULL) {
printf("Cannot open input file %s\n", "data_a5.txt");
exit(1);
}
for (size_arr = 0; fscanf(in, "%d", &value) == 1; size_arr++)
continue;
rewind(in);
int *arr = calloc(2 * size_arr + 1, sizeof(*arr));
if (arr == NULL) {
printf("Cannot allocate memory for %d entries\n", size_arr);
exit(1);
}
start = size_arr;
for (n = 0; n < size_arr && fscanf(in, "%d", &value) == 1; n++) {
/* insert value into the sorted array */
int a, b;
for (a = start, b = start + n; a < b;) {
int mid = a + (b - a) / 2;
if (arr[mid] < value) {
a = mid + 1;
} else {
b = mid;
}
}
/* insert value at offset b */
if (b - start < start + n - b) {
/* shift left portion to the left */
for (int i = start--; i < b; i++) {
arr[i - 1] = arr[i];
}
b--;
} else {
/* shift right portion to the right */
for (int i = start + n + 1; --i > b;) {
arr[i] = arr[i - 1];
}
}
arr[b] = value;
}
fclose(in);
print_array(arr + start, n);
free(arr);
return 0;
}
like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printArray(int arr[], int len){
while(len--)
printf("%d ", *arr++);
printf("\n");
}
int main(void){
int size_arr = 10;
int arr[size_arr];
int sort_arr[2 * size_arr + 1];
for(int i = 0; i < size_arr; ++i)
arr[i] = -50 + rand() % (100 + 1);
puts("before:");
printArray(arr, size_arr);
int left, right;
sort_arr[left = right = size_arr] = arr[0];
for (int n = 1; n < size_arr; ++n){
int v = arr[n];
if(v <= sort_arr[left]){
sort_arr[--left] = v;
} else if(v >= sort_arr[right]){
sort_arr[++right] = v;
} else {
int L = left, R = right, M, MV;
while(L <= R){
M = L + (R-L)/2;
MV = sort_arr[M];
if(MV < v)
L = M + 1;
else if(v < MV)
R = M - 1;
else
break;
}
//M: insert position
enum { LEFT, RIGHT } CHOICE;
if(v == MV){
int ML = M, MR = M;
while(sort_arr[ML-1] == sort_arr[ML])
--ML;
while(sort_arr[MR] == sort_arr[MR+1])
++MR;
if( ML-left >= right-MR){
M = MR+1;
CHOICE = RIGHT;
} else {
M = ML;
CHOICE = LEFT;
}
} else if(v > MV){
++M;
CHOICE = M-left+1 > right-M;// ? RIGHT : LEFT;
} else {
CHOICE = M-left-1 > right-M;// ? RIGHT : LEFT;
}
if(CHOICE == RIGHT){
memmove(sort_arr + M+1, sort_arr + M, (right-M+1)*sizeof(v));
sort_arr[M] = v;
++right;
} else {
memmove(sort_arr + left-1, sort_arr + left, (M-left)*sizeof(v));
sort_arr[M-1] = v;
--left;
}
}
}
puts("after:");
printArray(sort_arr + left, size_arr);
return 0;
}

Trouble with pset3 game of fifteen

My functions (init,draw,move and win) are not working properly. Can anyone shed some light on where I am going wrong?
init - should initialer the board and swap 1 and 2.
draw - should draw the current state of the board.
move - should move the tile if not illegal move.
win - should check the board if its in descending order.
/**
* fifteen.c
*
* Computer Science 50
* Problem Set 3
*
* Implements Game of Fifteen (generalized to d x d).
*
* Usage: fifteen d
*
* whereby the board's dimensions are to be d x d,
* where d must be in [DIM_MIN,DIM_MAX]
*
* Note that usleep is obsolete, but it offers more granularity than
* sleep and is simpler to use than nanosleep; `man usleep` for more.
*/
#
define _XOPEN_SOURCE 500
# include < cs50.h > #include < stdio.h > #include < string.h > #include <
stdlib.h > #include < unistd.h >
// constants
#define DIM_MIN 3# define DIM_MAX 9
// board
int board[DIM_MAX][DIM_MAX];
// dimensions
int d;
// prototypes
void clear(void);
void greet(void);
void init(void);
void draw(void);
bool move(int tile);
bool won(void);
void metrytoexchange(int * a, int * b);
int main(int argc, string argv[]) {
// ensure proper usage
if (argc != 2) {
printf("Usage: fifteen d\n");
return 1;
}
// ensure valid dimensions
d = atoi(argv[1]);
if (d < DIM_MIN || d > DIM_MAX) {
printf("Board must be between %i x %i and %i x %i, inclusive.\n",
DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX);
return 2;
}
// open log
FILE * file = fopen("log.txt", "w");
if (file == NULL) {
return 3;
}
// greet user with instructions
greet();
// initialize the board
init();
// accept moves until game is won
while (true) {
// clear the screen
clear();
// draw the current state of the board
draw();
// log the current state of the board (for testing)
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
fprintf(file, "%i", board[i][j]);
if (j < d - 1) {
fprintf(file, "|");
}
}
fprintf(file, "\n");
}
fflush(file);
// check for win
if (won()) {
printf("ftw!\n");
break;
}
// prompt for move
printf("Tile to move: ");
int tile = GetInt();
// quit if user inputs 0 (for testing)
if (tile == 0) {
break;
}
// log move (for testing)
fprintf(file, "%i\n", tile);
fflush(file);
// move if possible, else report illegality
if (!move(tile)) {
printf("\nIllegal move.\n");
usleep(500000);
}
// sleep thread for animation's sake
usleep(500000);
}
// close log
fclose(file);
// success
return 0;
}
/**
* Clears screen using ANSI escape sequences.
*/
void clear(void) {
printf("\033[2J");
printf("\033[%d;%dH", 0, 0);
}
/**
* Greets player.
*/
void greet(void) {
clear();
printf("WELCOME TO GAME OF FIFTEEN\n");
usleep(2000000);
}
/**
* Initializes the game's board with tiles numbered 1 through d*d - 1
* (i.e., fills 2D array with values but does not actually print them).
*/
void init(void) {
// TODO
int i, j;
int k = d * d - 1;
for (i = 0; i < d; i++) {
for (j = 0; j < d; j++) {
board[i][j] = k--;
if (k % 2 != 0) {
break;
} else {
if ((board[i][j] == 2) && (board[i][j - 1] == 1))
metrytoexchange( & board[i][j], & board[i][j - 1]);
}
}
}
}
/**
* Prints the board in its current state.
*/
void draw(void) { // TODO
int k = d * d - 1;
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
board[i][j] = k--;
if (board[i][j] == 0) {
printf("_");
} else
printf("%d \t", board[i][j]);
}
printf("\n");
}
}
void metrytoexchange(int * a, int * b) {
int temp = * a; *
a = * b; *
b = temp;
}
/**
* If tile borders empty space, moves tile and returns true, else
* returns false.
*/
bool move(int tile) {
int k = d * d - 1;
int blank_space = 0;
//dont go beyond the grid
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
if (tile < k && tile > 0 && tile == board[i][j]) {
continue;
} else {
break;
}
//iterate to check the position of of blank tile;left to right up and down if not return false
if (board[i - 1][j] != blank_space || board[i][j - 1] !=
blank_space || board[i + 1][j] != blank_space || board[i][j +
1
] != blank_space) {
return false;
}
//else swap tile with blank_space
else {
metrytoexchange( & tile, & blank_space);
return true;
}
}
}
return false;
}
/**
* Returns true if game is won (i.e., board is in winning configuration),
* else false.
*/
bool won(void) {
// TODO
// creat a variable that increases as the loop condition increases.let it start from 1 increasing
int win_board[d][d];
for (int i = 0; i < d; i++) {
for (int j = 0; j < d; j++) {
if (win_board[i][j] == board[i][j]) {
return true;
} else {
return false;
}
}
}
return false;
}

Check to see if the diagonal wins in tic tac toe

I have been given the code for a tic tac toe game. I produced the code to check to see if the vertical will win and have tried to check the diagonal. I was able to check the primary diagonal but can't seem to determine how to check the secondary. I thought the code i have would work but it does not. The issue I am having begins on line 172
#include <stdio.h>
#include <stdlib.h> // rand(), srand()
#include <time.h> // time()
// Size of the board (square)
const int BOARD_SIZE = 3;
// Symbols used for the board
const char BLANK_SYMBOL = ' ';
const char COMP_SYMBOL = 'O';
const char HUMAN_SYMBOL = 'X';
// Human goes first
const int HUMANS_TURN = 0;
const int COMPUTERS_TURN = 1;
// Function prototypes
void initializeBoard(char board[BOARD_SIZE][BOARD_SIZE]);
int hasWon(char board[BOARD_SIZE][BOARD_SIZE], char mark);
int hasWonHorizontal(char board[BOARD_SIZE][BOARD_SIZE], char mark);
int hasWonVertical(char board[BOARD_SIZE][BOARD_SIZE], char mark);
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark);
void getComputerMove(char board[BOARD_SIZE][BOARD_SIZE]);
void getHumanMove(char board[BOARD_SIZE][BOARD_SIZE]);
void printBoard(char board[BOARD_SIZE][BOARD_SIZE]);
void clearScreen(void);
//
// The main function should not be changed
//
int main(void) {
char board[BOARD_SIZE][BOARD_SIZE];
int humanWon = 0; // boolean (0/1)
int computerWon = 0; // boolean (0/1)
int move = 0;
// Seed the random number generator
srand(time(0));
initializeBoard(board);
while ((move < (BOARD_SIZE * BOARD_SIZE)) && !humanWon && !computerWon) {
clearScreen();
if ((move % 2) == COMPUTERS_TURN) {
getComputerMove(board);
} else {
printBoard(board);
getHumanMove(board);
}
computerWon = hasWon(board, COMP_SYMBOL);
humanWon = hasWon(board, HUMAN_SYMBOL);
move++;
}
clearScreen();
printBoard(board);
if (humanWon) {
printf(">>>> You won!\n");
} else if (computerWon) {
printf("<<<< I won!\n");
} else { // move >= BOARD_SIZE * BOARD_SIZE
printf("==== A Draw\n");
}
return 0;
}
//
// Initialized the board to all BLANK_SYMBOL
//
void initializeBoard(char board[BOARD_SIZE][BOARD_SIZE]) {
int row;
for (row = 0; row < BOARD_SIZE; row++) {
int col;
for (col = 0; col < BOARD_SIZE; col++) {
board[row][col] = BLANK_SYMBOL;
}
}
}
//
// Determines if the 'mark' completely fills a row, column, or diagonal
// returns 1 if yes, 0 if no
//
int hasWon(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
return hasWonHorizontal(board, mark)
|| hasWonVertical(board, mark)
|| hasWonDiagonal(board, mark);
}
//
// Determines if the 'mark' completely fills a row
// returns 1 if yes, 0 if no
//
int hasWonHorizontal(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
int won = 0; // boolean (0/1). Assume lost until proven true
int row;
for (row = 0; row < BOARD_SIZE && !won; row++) {
int match = 1; // boolean (0/1)
int col;
for (col = 0; col < BOARD_SIZE; col++) {
if (board[row][col] != mark) {
match = 0;
}
}
won = match;
}
return won;
}
//
// Determines if the 'mark' completely fills a column
// returns 1 if yes, 0 if no
//
int hasWonVertical(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
int won = 0;
int col;
for (col = 0; col < BOARD_SIZE && !won; col++) {
int match = 1;
int row;
for (row = 0; row< BOARD_SIZE; row++) {
if(board[row][col] != mark) {
match = 0;
}
}
won = match;
}
return won; // Stub -- make this return the correct value
}
//
// Determines if the 'mark' completely fills a diagonal
// returns 1 if yes, 0 if no
//
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
int won = 0;
int match = 1;
int col;
for (col = 0; col < BOARD_SIZE && !won; col++) {
if(board[col][col] != mark) {
match=0;
}
else if(board[BOARD_SIZE-col-1][col] != mark){
match=0;
}
}
won = match;
return won; // Stub -- make this return the correct value
}
//
// Gets computer move by randomly picking an unoccupied cell
//
void getComputerMove(char board[BOARD_SIZE][BOARD_SIZE]) {
int row;
int col;
do {
row = rand() % BOARD_SIZE;
col = rand() % BOARD_SIZE;
} while (board[row][col] != BLANK_SYMBOL);
board[row][col] = COMP_SYMBOL;
}
//
// Gets human move by prompting user for row and column numbers
//
void getHumanMove(char board[BOARD_SIZE][BOARD_SIZE]) {
int rowu;
int colu;
printf("Select the value of the row for your move: ");
scanf("%i", &rowu);
printf("Select the value of the column for you move: ");
scanf("%i", &colu);
board[rowu][colu] = HUMAN_SYMBOL;
}
//
// Prints the board to the screen. Example:
//
// 0 1 2
// +---+---+---+
// 0 | X | | |
// +---+---+---+
// 1 | | O | O |
// +---+---+---+
// 2 | | | X |
// +---+---+---+
//
void printBoard(char board[BOARD_SIZE][BOARD_SIZE]) {
printf(" 0 1 2\n");
printf(" +---+---+---+\n");
printf("0| %c | %c | %c |\n",board[0][0],board[0][1],board[0][2]);
printf(" +---+---+---+\n");
printf("1| %c | %c | %c |\n",board[1][0],board[1][1],board[1][2]);
printf(" +---+---+---+\n");
printf("2| %c | %c | %c |\n",board[2][0],board[2][1],board[2][2]);
printf(" +---+---+---+\n");
}
//
// Clears the screen -- uses ANSI terminal control codes
//
void clearScreen(void) {
const char ESC = 27;
printf("%c[2J%c[H", ESC, ESC);
}
The logic of your code is wrong. You are only checking the secondary diagonal if the cell on the primary diagonal does not equal mark.
You will need two separate variables to keep track of whether there is a victory on each diagonal. Your code should look like this:
int match_prime = 1, match_second = 1;
for(col = 0;col < BOARD_SIZE;++col){
match_prime = board[col][col] == mark;
match_second = board[BOARD_SIZE - col - 1][col] == mark;
}
won = match_prime || match_second;
Approach 1
Hard code the diagonal element indices.
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
int won = 0;
int match = 0;
if ( ( board[0][0] == mark &&
board[1][1] == mark &&
board[2][2] == mark ) &&
( board[0][2] == mark &&
board[1][1] == mark &&
board[2][0] == mark ) )
{
match = 1;
}
won = match;
return won; // Stub -- make this return the correct value
}
Approach 2
Use for loops and iterate over the indices.
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark) {
int match = 1;
int won = 0;
int row = 0;
// Check the first diagonal.
for (row = 0; row < BOARD_SIZE && !won; row++) {
if(board[row][row] != mark) {
match=0;
}
}
// If the first diagonal check already produces a match,
// there is no need to check the second diagonal.
if ( match != 1 )
{
int col = BOARD_SIZE-1;
for (row = 0; row < BOARD_SIZE && !won; row++, col--) {
if(board[row][col] != mark){
match=0;
}
}
}
won = match;
return won; // Stub -- make this return the correct value
}
The functions can look the following way
//
// Determines if the 'mark' completely fills a row
// returns 1 if yes, 0 if no
//
int hasWonHorizontal( char board[BOARD_SIZE][BOARD_SIZE], char mark )
{
int won = 0; // boolean (0/1).
for ( int row = 0; row < BOARD_SIZE && !won; row++ )
{
int col = 0;
while ( col < BOARD_SIZE && board[row][col] == mark ) ++col
won = col == BOARD_SIZE;
}
return won;
}
//
// Determines if the 'mark' completely fills a column
// returns 1 if yes, 0 if no
//
int hasWonVertical( char board[BOARD_SIZE][BOARD_SIZE], char mark )
{
int won = 0;
for ( int col = 0; col < BOARD_SIZE && !won; col++ )
{
int row = 0;
while ( row < BOARD_SIZE && board[row][col] == mark ) ++row;
won = row == BOARD_SIZE;
}
return won; // Stub -- make this return the correct value
}
//
// Determines if the 'mark' completely fills a diagonal
// returns 1 if yes, 0 if no
//
int hasWonDiagonal(char board[BOARD_SIZE][BOARD_SIZE], char mark)
{
int won = 0;
int i = 0;
while ( i < BOARD_SIZE && board[i][i ] == mark ) ++i;
won = i == BOARD_SIZE;
if ( !won )
{
i = 0;
while ( i < BOARD_SIZE && board[i][BOARD_SIZE - i - 1 ] == mark ) ++i;
won = i == BOARD_SIZE;
}
return won; // Stub -- make this return the correct value
}

Resources