What Are Loops?

mla apa chicago
Your Citation
Leahy, Paul. "What Are Loops?" ThoughtCo, Apr. 30, 2017, thoughtco.com/loops-2034224. Leahy, Paul. (2017, April 30). What Are Loops? Retrieved from https://www.thoughtco.com/loops-2034224 Leahy, Paul. "What Are Loops?" ThoughtCo. https://www.thoughtco.com/loops-2034224 (accessed September 24, 2017).
Man working on a computer
Tim Robbins/Mint Images RF/Getty Images

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.


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;
 System.out.println("We've found the number after " + index + " loops");

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