Introduction to Loops
In the programming world, we hate repeating ourselves. There are two reasons for this:
- Writing the same code over and over is time-consuming.
- Having less code means having less to debug.
But we often need to do the same task more than once. Fortunately, computers are really good (and fast) at doing repetitive tasks. And in Java, we can use loops.
A loop is a programming tool that allows developers to repeat the same block of code until some condition is met. We employ loops to easily scale programs, saving time, and minimizing mistakes.
We’ll go over three types of loops that you’ll see everywhere:
while
loopsfor
loops- for-each loops
While We're Here
Awhile
loop looks a bit like anif
statement:while (silliness > 10) { // code to run
}Like anif
statement, the code inside awhile
loop will only run if the condition istrue
. However, awhile
loop will continue running the code over and over until the condition evaluates tofalse
. So the code block will repeat untilsilliness
is less than or equal to 10.// set attempts to 0 int attempts = 0; // enter loop if condition is true while (passcode != 8109 && attempts < 3) { System.out.println("Please Try again."); passcode = getNewPasscode(); attempts += 1; //tushargahora.blogspot.com // is condition still true? // if so, repeat code block } // exit when condition is not truewhile
loops are extremely useful when you want to run some code until a specific change happens. However, if you aren’t certain that change will occur, beware of the infinite loop!Infinite loops occur when the condition will never evaluate tofalse
. This can cause your entire program to crash.int legs = 5; // This will cause an infinite loop: while (legs < 6) { System.out.println("Not enough legs!"); }In the example above,legs
remains equal to5
, which is less than6
. So we would get an infinite loop.Incrementing While Loops
When looping through code, it’s common to use a counter variable. A counter (also known as an iterator) is a variable used in the conditional logic of the loop and (usually) incremented in value during each iteration through the code. For example:// counter is initialized int wishes = 0; // conditional logic uses counter while (wishes < 3) { System.out.println("Wish granted."); // counter is incremented wishes++; }In the above example, the counterwishes
gets initialized before the loop with a value of0
, then the program will keep printing"Wish granted."
and adding1
towishes
as long aswishes
has a value of less than3
. Oncewishes
reaches a value of3
or more, the program will exit the loop.So the output would look like:Wish granted. Wish granted. Wish granted.We can also decrement counters like this:int pushupsToDo = 10; while (pushupsToDo > 0) { doPushup(); pushupsToDo--; }In the code above, the counter,pushupsToDo
, starts at 10, and increments down one at a time. When it hits 0, the loop exits.For Loops
Incrementing with loops is actually so common in programming that Java (like many other programming languages) includes syntax specifically to address this pattern:for
loops. Afor
loop brings together the following steps in a single line, separated by semicolons:- Initializing a counter variable.
- Defining the looping condition.
- Incrementing the counter.
The opening line might look like this:for (int i = 0; i < 5; i++) { // code that will run }i = 0
:i
is initialized to0
.i < 5
: the loop is given a condition that relies on the value ofi
.i++
:i
will increment at the end of each loop.
So the code will run through the loop a total of five times.You’ll also hear the term “iteration” in reference to loops. When you iterate, it just means that you are repeating the same block of code.Using For Loops
for
loops aren’t just a nice syntax, they also help us remember to increment our counter — something that is easy to forget when we increment with awhile
loop. Leaving out that line of code would cause an infinite loop — yikes!Fortunately, equipped with your new understanding offor
loops, you can help prevent infinite loops in your own code.Iterating Over Arrays and ArrayLists
One common pattern you’ll encounter as a programmer is looping through a list of data and doing something with each item. In Java, that list would be an array orArrayList
and the loop could be afor
loop. But wait, how does this work?for
loops begin with a counter variable. We can use that counter to track the index of the current element as we iterate over the list of data.Because the first index in an array orArrayList
is 0, the counter would begin with a value of0
and increment until the the end of the list. So we can increment through the array orArrayList
using its indices.For example, if we wanted to add1
to everyint
item in an arraysecretCode
, we could do this:for (int i = 0; i < secretCode.length; i++) { secretCode[i] += 1; }Notice that our condition in this example isi < secretCode.length
. Because array indices start at 0, the length ofsecretCode
is 1 larger than its final index. Therefore, the loop should stop when it is less than BUT NOT equal to the length value.In the case of anArrayList
, this code would look like:for (int i = 0; i < secretCode.size(); i++) { int num = secretCode.get(i); secretCode.set(i, num + 1); }
For-Each Loops
- Sometimes we need access to the elements’ indices or we only want to iterate through a portion of a list. If that’s the case, a regular
for
loop is a great choice. But sometimes we couldn’t care less about the indices; we only care about the element itself. At times like these, for-each loops come in handy.For-each loops allow you to directly loop through each item in a list of items (like an array orArrayList
) and perform some action with each item. The syntax looks like this:for (String inventoryItem : inventoryItems) { System.out.println(inventoryItem); }We can read the:
as “in” like this: for eachinventoryItem
(which should be aString
) ininventoryItems
, printinventoryItem
.Note that we can name the individual item whatever we want; using the singular of the plural is just a convention. You may also encounter conventions likeString word : sentence
.
No comments: