0

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!

2
Contributors
4
Replies
17
Views
1 Year
Discussion Span
Last Post by glao
0

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.)

0

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!!

0

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?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.