Search code examples
c++cxcodechess

How to make a chessboard in C?


I am new to C and I am trying to make a program that would output a chessboard pattern. But, I don't understand what my next steps are going to be . Could anyone help me with this?

Main:

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

int main() {
    int length,width;
    enum colors{Black,White};

    printf("Enter the length:\n");
    scanf("%d",length);
    printf("Enter the width:\n");
    scanf("%d",width);

    int board[length][width];
    createBoard(length,width);
    for(int i =0;i< sizeof(board);i++) {

        if(i%2==0) {
            // To print black
            printf("[X]");
        }
        else {
            // To print white
            printf("[ ]");
        }
    }
} //main

CreateBoard function:

int createBoard(int len, int wid){
    bool b = false;
    for (int i = 0; i < len; i++ ) {
        for (int j = 0; j < wid; j++ ) {
            // To alternate between black and white
            if(b = false) {
                board[i][j] = board[White][Black];
                b = false;
            }
            else {
                board[i][j] = board[Black][White];
                b = true;
            }
        }
    }
    return board;
}

Solution

  • Firstly learn how to use scanf().

    int length;
    

    Incorrect : scanf("%d",length); Correct : scanf("%d",&length);

    Hope this helps:

    #include <stdio.h>
    
    int main(void) 
    {
        int length,width,i,j;
        printf("Enter the length:\n");
        scanf("%d",&length);
        printf("Enter the width:\n");
        scanf("%d",&width);
        for(i=1;i<=length;i++)
        {
            for(j=1;j<=width;j++)
            {
                if((i+j)%2==0)
                    printf("[X]");
                else printf("[ ]");
            }
            printf("\n");
        }
        return 0;
    }
    

    Note: Make sure length and width are of even length.