What are Loops?

edit

Loops are a handy tool that enables programmers to do repetitive tasks with minimal effort.

Consider the following application.

Print the numbers 1 to 10.

  Code:

class Count {
    public static void main(String[] args) {
        System.out.println('1 ');
        System.out.println('2 ');
        System.out.println('3 ');
        System.out.println('4 ');
        System.out.println('5 ');
        System.out.println('6 ');
        System.out.println('7 ');
        System.out.println('8 ');
        System.out.println('9 ');
        System.out.println('10 ');
    }
}

  Output:

1
2
3
4
5
6
7
8
9
10
The above code is the output

The task will be completed just fine, the numbers 1 to 10 will be printed in the output, but there are a few problems with this solution:

  • Flexibility, what if we wanted to change the start number or end number? We would have to go through and change them, adding extra lines of code where they're needed.
  • Scalability, 10 repeats are trivial, but what if we wanted 100 or even 1000 repeats? The number of lines of code needed would be overwhelming for a large number of iterations.
  • More error prone, where there is a large amount of code, one is more likely to make a mistake.

Using loops we can solve all these problems. Once you get you head around them they will be invaluable to solving many problems in programming.

Open up your editing program and create a new file. Now type or copy the following code:

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


This code may look confusing to you if you have never encountered a loop before, don't worry, the exact details of different loops will be explained later in this chapter, this is an aid to illustrate the advantages of loops in programming.

If we run the program, the same result is produced, but looking at the code, we immediately see the advantages of loops. 10 lines of code have been reduced to just 4. Furthermore, we may change the number 10 to any number we like. Try it yourself, replace the 10 with your own number.

While Loops

edit

While

edit

Do-While

edit

For Loops

edit