Loop

# Definition

A loop is a programming construct that takes a statement or block of statements and repeats it as a long as its condition is true.

# Nested Loops

A nested loop is a loop that is placed inside another loop.

## Independent Nesting

A program which creates multiplication tables is a great example of using nested loops.

```int x = 4;
for(int i = 1; i <= x; i++){
for(int j = 1; j <= x; j++){
System.out.print(i * j + "\t");
}
System.out.println("\n");
}
```

Everytime the outer for loop runs, the inner one will run x times for a total of x * x times in this case.

## Dependent Nesting

In other cases, where the outer loop runs x times and the inner loop runs y times they will combine for a total of x * y repetitions. Of course, this can be further complicated by one loop's counting being dependent on another loop's counting. As in the following example:

```for(int i = 0; i < 3; i++){
for(int j = 0; j <= i; j++){
System.out.print("*")
}
System.out.println();
}
```

In the example above, j is dependent on i since the second loop will only run as long as j <= i. In this case, we start with i = 0. Now since j = 0 and is equal to , the loop will print a "*". We then add 1 to j. Now j = 1 and i still equals , so the program will print a new line and return to the first loop. Thus, if you run through the whole program for i, it should look like this:

```*
**
***
```

## Levels of Nesting

You can also have more than two levels of nesting.

## Nested Loops and Tables

Generally, when using nested loops to print out a table, the outer loop will control the movement along the rows and the inner loop will control the movement along the columns.

# Infinite Loops

For almost all programs, infinite loops are not wanted. Example of infinite loop:

```int n = 0;
for(int i = 1; i < 100; i += 0) {
n++;
}
```

In the case above, the loop will run until i >= 100 but since you are adding to i, i will always be zero and the loop will never end. Infinite loops are more common with while loops where the body of the loop never changes any of the values in the condition.

# Tips

## Empty Loops

Watch out for creating a loop with no statement, or more correctly, a loop with an empty statement. When this happens it is almost always the result of the mistaken placement of a semicolon at the end of the loop condition and is almost always an unintended error. The loop below will run ten times without performing any statements (actually, it will run the empty statement ten times) but x will only be incremented once after the loop is done.

```int x = 0;
for(int i = 0; i < 10; i++);
x++;
```

## While vs. For

When you know how many times you want to loop through, you should use a for loop. When you are not sure how many times you want to loop through, a while loop is best.

Example for a for loop thanks to JavaBat:

Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.

```public int countEvens(int[] nums) {
int count = 0;
for(int i = 0; i < nums.length; i ++) {
if(Math.abs(nums[i] % 2) != 1) {
count ++;
}
}
return count;
}
```

Since we know that we want to loop through i as long as i < nums.length a for loop is best.

Example for a while loop thanks to Zev Shimko:

```int num = 10;
int base = 2;

while (num/base != 0) {
num = num/base;
System.out.print (num%base);
}
```

Since we don't necessarily know exactly how many times num / base != 0, a while loop is best for this situation.

## Avoid Jumping Over Your Condition

When using a loop, it is always better to use < instead of != in your condition. Sometimes you may want to change the update section of the loop (e.g. use i+=2 instead of i++). If you use != you may accidentally jump right over your stopping condition (nums.length in this case). Using < will alleviate this problem.

For example, if you originally want to set the values of the elements of the array x to their corresponding indices:

```for(int i = 0; i != nums.length; i++) {
x[i] = i;
}
```

But then you change your mind and decide to set only every other element's value to its corresponding index:

```for(int i = 0; i != nums.length; i += 2) {
x[i] = i;
}
```

This code will work fine if x's length is even, but if the length is odd it will skip over nums.length and crash with an ArrayIndexOutOfBounds exception. In other cases it could cause an infinite loop.

To avoid these types of problems just use < instead:

```for(int i = 0; i < nums.length; i += 2) {
x[i] = i;
}
```

This code works whether x's length is even or odd.

## Always Use Curly Braces

Theoretically, a loop body can be either a statement or a block of code enclosed in {}'s. However, we always enclose a loop's code within {}'s regardless of its length. This way you will never forget to add {}'s when you change your loop body from one line to several lines.