1. Technology
Send to a Friend via Email

Loops

By

Man working on a computer
Tim Robbins/Mint Images RF/Getty Images
Definition:

A loop is a way of repeating lines of code more than once. The block of code contained within the loop will be executed again and again until the condition required by the loop is met. For example, you could set up a loop to print out the even numbers between 1 and 100. The code that gets executed each time the loop is run will be the printing out of an even number, the condition the loop is looking to meet is reaching 100 (i.e., 2 4 6 8....96 98).

There are two types of loops:

  • Indeterminate - an indeterminate loop does not know how many times it will run. For example, you could search through an int array looking for a specific value. The most logical way would be to search each element of the array in order until you find the right value. You don't know if the value is in the first element or the last so the number of times you loop around checking the next element of the array is unknown. Indeterminate loops are the while and do..while loops.
  • Determinate - a determinate loop knows exactly how many times it will loop. For example, if you want to know how much money you'll be paid for the next twelve months minus tax you could perform the wage calculation 12 times. The determinate loop in Java is the for loop.

Examples

An indeterminate while loop to search for the number 10 in a randomly ordered int array:

//int array of random numbers
int[] numbers = {1, 23, 56, 89, 3, 6, 9, 10, 123};
        
//a boolean variable that will act as the condition for the loop
boolean numberFound = false;
int index = 0;
//this loop will continue running until numberFound = true
while (!numberFound)
{
   System.out.println("We're looping around..");
   if (numbers[index] == 10)
   {
      numberFound = true;
      index++;
      System.out.println("We've found the number after " + index + " loops");
   }
   index++;
}

A determinate for loop to display all the even numbers between 1 and 100:


int number = 0;
//loop around 49 times to get the even numbers
//between 1 and 100
for (int i=1;i<50;i++)
{
    number = number + 2;
    System.out.println("loop number: " + i + " for even number: " + number);
}

Glossary:

# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

  1. About.com
  2. Technology
  3. Java
  4. Java Glossary
  5. L
  6. Definition for the Java Term: Loops

©2014 About.com. All rights reserved.