Saturday, 25 August 2012

Java programming lesson #4 - Loops


A loop is a way of repeating lines of code. If you want to for example print Hello on the screen 10 times then you can either use System.out.println 10 times or you can put 1 System.out.println in a loop that runs 10 times which takes a lot less lines of code.

For loop

The for loop goes from a number you give it to a second number you give it. It uses a loop counter variable to store the current loop number. Here is the format for a for loop:

for (set starting value; end condition; increment loop variable)

You first set the loop counter variable to the starting value. Next you set the end condition. While the condition is true the loop will keep running but when it is false then it will exit the loop. The last one is for setting the amount by which the loop variable must be increased by each time it repeats the loop. Here is how you would do the example of printing Hello 10 times using a for loop:

public class Loops
{
   public static void main(String[] args)
   {
      int i;
      for (i = 1; i <=10; i++)
         System.out.println("Hello");
   }
}

Incrementing and decrementing

i++ has been used to add 1 to i. This is called incrementing. You can decrement i by using i--. If you use ++i then the value is incremented before the condition is tested and if it is i++ then i is incremented after the condition is tested.

Multiple lines of code in a loop

If you want to use more than 1 line of code in a loop then you must group them together between curly brackets.
public class Loops
{
   public static void main(String[] args)
   {
      int i;
      for (i = 1; i <=10; i++)
      {
         System.out.println("Hello");
         System.out.println(i);
      }
   }
}

While loop

The while loop will repeat itself while a certain condition is true. The condition is only tested once every loop and not all the time while the loop is running. If you want to use a loop counter variable in a while loop then you must initialize it before you enter the loop and increment it inside the loop. Here is the Hello example using a while loop:

public class Loops
{
   public static void main(String[] args)
   {
      int i = 1;
      while (i <= 10)
      {
         System.out.println("Hello");
         i++;
      }
   }
}

Do while loop

The do while loop is like the while loop except that the condition is tested at the bottom of the loop instead of the top.

public class Loops
{
   public static void main(String[] args)
   {
      int i = 1;
      do
      {
         System.out.println("Hello");
         i++;
      }
      while (i <= 10)
   }
}

0 comments:

Post a Comment