battle black blur board game
Javascript Programming

How to make Chessboard using Javascript?

Problem:

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chessboard.

Passing this string to console.log should show something like this:

 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # #

When you have a program that generates this pattern, define a binding size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

My solution:

let main_row = "";
let main_row_1 = ""
let main_size = 10;

for(i=0; main_row.length< main_size; i++){
    if(i%2){
        main_row = main_row + " #"
       } 
    main_row = main_row + "";
}

for(i=0; main_row_1.length< main_size; i++){
    if(i%2){
        main_row_1 = main_row_1 + "# "
       } 
    main_row_1 = main_row_1 + "";
}



let row = main_row_1;
let row_space=main_row;


for(let k = 0; k<=main_size -1; k++){
    if(k%2===0){
        console.log(row)
    }else{
        console.log(row_space)
    }
}

Leave a Reply