Saturday, August 14, 2010

5. The for loop

Loops are an incredibly important part of java and that's why I'm going to teach you about them!  There are two very important loops but I'll teach you about them separately.  So here goes for the for loop.

A loop is basically something that loop, or repeats, itself over and over.  It is useful if you need to do something 5 times and don't want to write the code 5 times.

Here's the format of a for loop

for(int i = 0; i < 10; i+=1) {
    (this is the stuff that the loop will do)
}

Some of this stuff will be new but don't worry.  
So let's start from the beginning, I basically said do whatever is inside the loop ten times.
The very first part of the loop is int i = 0; Now you know that semicolons end things so all this statement does is create an int called i that contains 0.  
The second part  is  i < 10; and this is the part that keeps the loop going however many times you specify it should loop.  I said that it should loop while i is less than ten so since i started at 0 it should loop ten times!
The third part is i+=1 notice that this doesn't have a semicolon.  Because it is the last statement of the for loop it doesn't need one, that's just the way that java works.  Anyways this statement adds 1 to i.  So it will increment i by one.  If I had said i+=2 then it would have incremented i by two every time and the for loop would only run 5 times.

Now that we know about for loops lets demonstrate their awesomeness!!!!
Create a class called forloop and create your main method then post this code inside the main method.

for(int i = 0; i < 10; i+=1) {
            System.out.println(i);
}

Now run it and then make i increment by two instead of one and see what happens.  Make the for loop run up to 1000 if you want.  Drop a comment if you need any help, Thanks! 

4 comments:

  1. can you please talk more on how the increment works,because i don't understand other forms of incrementation,and explain y this code below is giving me 28 thanks


    double a=1.0;
    for(int j=0;j<9:j++)
    {
    a*=3;
    }
    System.out.println(j);

    ReplyDelete
  2. I don't understand how this code would work. You try to print out j but you shouldn't be able to because you won't be able to access it. Can you post the rest of your code?

    ReplyDelete
  3. I just don't understand how the incrementation works....Can you please explain how it works and when and how to use then?

    ReplyDelete
  4. Okay so in the first part of a for loop you create a variable:
    int j = 0;
    Then, then, in the second part you tell it when it should run:
    j<9;
    So when j is less than 9 the for loop will run, if j is greater than or equal to 9 then the loop will stop.
    In the third part you tell it what to do at the end of each time it loops, here you say:
    j++
    j++ just means add 1 to whatever j is right now, it is the equivalent of j+=1!

    ReplyDelete