samedi 3 février 2018

For loop count 1 to 10 and then 10 to 1 alternatively, concatenated with a letter

How can I write a code with nested for-loop, that gives the following result:

W,1,1
W,1,2
W,1,3
W,1,3
W,1,2
W,1,1
W,2,1
W,2,2
W,2,3
W,2,3
W,2,2
W,2,1
etc...

Note: These numbers are not always odd and even numbers, they may be decimal, but they are so here for simplifying

I tried this, but wrong results:

var lon,lat,str ='',i = 0;

    for(lat=1; lat<=2; lat++)
    {
    if((i%2)==0){

        for(lon=1; lon<=3; lon++)
           {

            str+="W,"+lat+","+lon+"\n";
            console.log(str)
           }
               }
    else{

         for(lon=3; lon>=1; lon--)
           {

            str+="W,"+lat+","+lon+"\n";
            console.log(str)
           }
              }
                i++;   
         }

I thought, I would take a variable i as intermediate, with each time loop it is either odd or even via increment, then with If...Else I would decide when it should be counted forward or backwards.

Any idea

Please, coding with Java or Javascript, thx

Aucun commentaire:

Enregistrer un commentaire