Computer Science Canada

For loops

Author:  cool dude [ Fri May 05, 2006 6:56 pm ]
Post subject:  For loops

can someone please tell me what the difference is between doing it these 2 ways? because the first way doesn't work and i don't see much of a difference Confused

code:

public class listnums1
{
        public static void listnums1(int max){
          int i = 0;
          for (i; i<=max; i++){
              System.out.println("Number: " + i);
           }
}
}



Or the correct way

code:

{
        public static void listnums1(int max){
          for (int i = 0; i<=max; i++){
              System.out.println("Number: " + i);
           }
}
}

Author:  Tony [ Fri May 05, 2006 8:14 pm ]
Post subject: 

well because it's like

for ( declare local? variable; condition; some operation)

so placing i where variable declaration is expected instead is wrong

I think that
code:

int i = 0;
     for (; i<=max; i++){

might work, it should in C Laughing

just be careful about your counter's scope

Author:  rizzix [ Fri May 05, 2006 8:45 pm ]
Post subject:  Re: For loops

cool dude wrote:
code:
public class listnums1
{
        public static void listnums1(int max){
          int i = 0;
          for (i; i<=max; i++){
              System.out.println("Number: " + i);
           }
}
}
The first part of the for-loop has to be either an initialization or an assignment. Your code clearly breaks that rule.

Maybe you meant this:
code:
public class listnums1
{
        public static void listnums1(int max){
          int i;
          for (i = 0; i<=max; i++){
              System.out.println("Number: " + i);
           }
    }
}

Author:  cool dude [ Fri May 05, 2006 8:57 pm ]
Post subject: 

so this is one of those pointless rules. i don't really see much of a difference in declaring a variables and then making the counted/for loop with it. thanks for explaining Smile

P.S. how would you draw shapes in java? Confused

Author:  [Gandalf] [ Sat May 06, 2006 12:38 am ]
Post subject: 

cool dude wrote:
P.S. how would you draw shapes in java? Confused

You create either an applet or a Frame, JFrame, or some other kind of GUI container, and use the paint() method using the Graphics class.

Author:  rizzix [ Sat May 06, 2006 3:11 pm ]
Post subject: 

cool dude wrote:
so this is one of those pointless rules. i don't really see much of a difference in declaring a variables and then making the counted/for loop with it.
It's not really a pointless rule. It is a rule.

If you wish you may also write that snippet as follows:
code:
public class listnums1
{
   public static void listnums1(int max){
     int i = 0;
     for (; i<=max; i++){
         System.out.println("Number: " + i);
      }
}


See the difference?...


: