Java Tutorial: For Loop

Every Tuesday I take some time to put together a java tutorial.  You will notice at the top there is a page indexing them all.  Enjoy!

Welcome back everyone!  Today is going to be a pretty short tutorial as it is only going over one topic.  Although this topic is pretty important and I consider it part one, as you will see next week.  But enough chit chat, lets get into for loops!

When a programmer want to repeat a piece of code until a certain constraint is met a for loop might be the answer!  What it does is sets up a chunk of code that gets repeated until the for statement is false.  Here is an example of a for loop

int i;

for (i = 0; i < 10; i++)


    //Any code you want to repeat goes here

    System.out.println("This is the " + i + " time through the loop");


This is this basic structure of the for loop.  There are three arguments that need to be met within the for statement, and they are separated by semicolons.  The first is the variable that will be iterated.  This is the integer variable i in this case and it is set to 0.  The next part is the statement that determines if the loop is done or not.  In this case, as long as the variable i is less than 10 the inner block of code will execute.  The last part is adding 1 to i every time it executes.  You can also do i– for decrement, or any other way to change the variable (might want to multiply it by 2 or something).

This last part of modifying the variable in some way is very important, and it needs to make logical sense.  You want to have some limit, otherwise you will find yourself caught in an infinite loop. Those are bad, so stay away from them!  If you do happen to get stuck in an infinite loop, terminate the program and look at how you defined the for loop to pin point the issue.

While the concept of this may seem silly or a little bit overkill for this far in the tutorial it will become a really amazing asset in the future, so practice your for loops now so they are second nature in the future!

Practice Problem

Okay, so this was a short tutorial but this practice problem should incorporate what you have learned so far!  Ask the user how many times they would like you to repeat a greeting, or any other saying you want.  Then use that to limit your for loop to repeat it that many times!


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: