Skip to content
trekitch edited this page Apr 23, 2017 · 10 revisions

Loops are useful to running code multiple times. Loops can be used to output number or to output strings a set number of times.

For loop

For loops are used to run a loop a specified amount of times. For example, let's say you wanted to output "Hello World" 10 times.

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

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

How it works

The for loop starts by first initializing the variable it will count. In this case, the variable i is initialized to 1. Next, the for loop is given an expression to compare the variable to. This expression tells the loop when to stop. In this case, it is when the variable i is greater than 10. Next, the body of the for loop runs and outputs "Hello World". Finally, the statement returns to the top and increases the variable by one. The process continues until i is greater than 10 and the loop exits.

While loops

While loops are a different type of loop. Unlike for loops, while loops do not initialize or increment any variables instead they just run while a certain condition is true.

Example:

int counter = 1;
while (counter> 10)
{
   System.out.println("This is less than 10");
   increment = increment + 2;
}

Even though you can perform similar procedures to for loop with while loops, while loops excel because they can run more statements inside of the body.

Do while loop

Do while loops are almost exactly the same as while loops except they run at least once before evaluating the expression. The syntax for do-while loops is also different.

Example:

do
{
   //statement to run
}
while(counter < 10)

As you can see the do while loop has the condition evaluated at the end. This makes sure that the statements in the body run at least once. This can come in handy when you need to make sure you at least output something to the user such as a greeting or instructions.

Uses of a Do-While loop

A do-while loop can be very useful for checking conditions. For example, if you have a program that you want to run until the user tells it to stop you could do this with a do-while loop.

do
{
            
            
     System.out.print("Please enter your name: ");
     userName = input.nextLine();
            
     System.out.print("Please enter your number: ");
     userNumber = input.nextInt();
            
     System.out.print("Pleae enter your age: ");
     userAge = input.nextInt();
            
     System.out.println("Hello " + userName + " you=r number is " + userNumber
            + " and your age is " + userAge);
            
     System.out.println("Enter 1 to continue program or 999 to quit");
     userInput = input.nextInt();
     input.nextLine();
            
}while(userInput != QUIT);

Output

Please enter your name: Bubba 
Please enter your number: 23
Please enter your age: 45
Hello Bubba  your number is 23 and your age is 45
Enter 1 to continue program or 999 to quit
1
Please enter your name: Ray
Please enter your number: 23
Please enter your age: 67
Hello Ray your number is 23 and your age is 67
Enter 1 to continue program or 999 to quit
999

As you can see this loop runs through the first time automatically. Then it asks the user if they want to continue or not. Based on what the user puts in the program goes from there.

Nested Loops

With loops, it is also possible to loop them just like decision structures. If you want to run a while loop inside of another loop, a for loop inside of a do-while, etc, you can. Nested loops work the same way as other nested statements. The innermost statement runs and once that is complete it exits and runs the second statement and so on and so one until the program finishes. Take this as an example.

for (int i = 1; i <= 5; i++)
 {   // outer loop iterates 5 times.
    for (int j = 1; j <= 10; j++) 
    {  // for each iteration of outer loop, 
        // inner loop iterates 10 times
        System.out.print((i * j) + " ");
    }
    System.out.println();
}

Output

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 

Explanation:

When the inside loop runs, the j loop, it runs until the variable j reaches the limit set. In this case, that limit is 10. After the inner loop completes it is exited and the println() statement is executed. Then the program returns to the outer loop, increases the i variable by one, performs the comparison and returns to the inner loop. This continues until the outer loop reaches its limit of five. If we were to just tweak the outer loops limit to something like 10 then it would look like this:

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
6 12 18 24 30 36 42 48 54 60 
7 14 21 28 35 42 49 56 63 70 
8 16 24 32 40 48 56 64 72 80 
9 18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100
Clone this wiki locally