Computer Science Canada

for loop

Author:  iluvchairs112 [ Mon Feb 26, 2007 6:37 pm ]
Post subject:  for loop

i'm getting confused with the for loop

int j = 3;
for (j=3;j<24;j*2)
{
j=j*2;
}
System.out.println(j);

what is wrong with the line: for (j=3;j<24;j*2)
how is it not a statement? I get that same problem every time i try to build it

Author:  Clayton [ Mon Feb 26, 2007 6:43 pm ]
Post subject:  Re: for loop

I'm not entirely sure here, but I think you have to declare j inside the for statement. Yours:

Java:

int j = 3
for(j = 3; j < 24; j * 2)
{
    //whatever
}


I believe should be:

Java:

for(int j = 3; j < 24; j * 2)
{
    //whatever
}


Also, I'm not entirely sure you can "increment" j the way you are, I believe you have to actually increment it (ie j++ or ++j or j-- or --j). Perhaps someone could clarify?

Author:  iluvchairs112 [ Mon Feb 26, 2007 6:50 pm ]
Post subject:  Re: for loop

my teacher just lately said that you could increment like that ... but I haven't been able to get it to work (but I wasn't sure why) ... thanks, I'll try that though

Author:  PaulButler [ Mon Feb 26, 2007 7:43 pm ]
Post subject:  RE:for loop

Change it to this:

Java:

int j = 3
for(j = 3; j < 24; j *= 2)
{
    //whatever
}


j * 2 should be j *= 2. This sets j to double. Otherwise, you are multiplying j by two but not telling it where to put the product.

Author:  HeavenAgain [ Wed Feb 28, 2007 9:07 pm ]
Post subject:  Re: for loop

code:

int j = 3;
for (j=3;j<24;j*2)
{
  j=j*2;
}
System.out.println(j);


is not a statement becuase you have to declear what j is, inside the for (..;..;..)
example:
for (int j;j<=24;j*=2)

the condition j*2 inside the for is not going to do anything unless you do an output inside the for loop

your output is going to be 3 beucase
code:

class ***
{
   int b // int b
   for (int a;..;..) //int b
         { // int a,int b
         }//end of int a, int b
}//end of int b

and is better if the 2 variable names are not the same, this way it wont confuse you Wink (or me)

Author:  PaulButler [ Wed Feb 28, 2007 9:31 pm ]
Post subject:  Re: for loop

HeavenAgain @ Wed Feb 28, 2007 9:07 pm wrote:
...you have to declear what j is, inside the for (..;..;..)


Actually, you can define j outside the loop and it will still work. It is not always the right way to do things, but it can come in handy in some situations when you need to access that variable outside the scope of the loop.


: