Hello ,
I am new to javascript and I have the following code in c :

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

int main()
{
    int height = 8, width = 8;
    for ( int i = 0; i < height; i++ )
    {

        for ( int j = 0; j < width; j++ )
        {
            if (i % 2 == 0)
            {
                if ( j % 2 == 0 ) printf("#");
                else printf(" ");
            }
            else
            {
                if ( j % 2 == 0 ) printf(" ");
                else printf("#");
            }
        }


        printf("\n");
    }


return 0;

}

which produces :

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

and I am trying in javascript:

var width = 8;
var height = 8;


for ( var i = 0; i < height; i++ )
{
    for ( var j = 0; j < width; j++ )
    {
        if ( i % 2 === 0 )
        {
            if ( j % 2 === 0 )
                console.log("#");
            else console.log(" ");
        }
        else
        {
            if ( j % 2 === 0 )
                console.log(" ");
            else console.log("#");
        }

    }
    console.log("\n");

}

which produces :

#

#

#

#




#

#

#

#
...

I can't figure why?
Is console.log the problem?

Thanks!

A quick glance at console.log shows it puts out a newline after each string.

So, build a string and when done, console.log that string (in line 23.)

Hmm.I didn't know that.Thanks.But , trying this :

var width = 8;
    var height = 8;
    var di = " ";


    for ( var i = 0; i < height; i++ )
    {
        for ( var j = 0; j < width; j++ )
        {
            if ( i % 2 === 0 )
            {
                if ( j % 2 === 0 )
                    di += "#";
                else di += " ";
            }
            else
            {
                if ( j % 2 === 0 )
                    di += " ";
                else di += "#";
            }
        }
         console.log(di);
    }

gives me:

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

What a confusion!!

Looks like it worked as coded. Since you never cleared your string, each loop added to it. Oh so close.
Maybe line 3 moves to after line 6?

Yes,ok!I missed that.
Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.