Java programming for beginners - Lesson 6 - While/Do While Loops
Hello everyone, welcome to the seventh lesson in my Java programming for beginners tutorials series. The sixth lesson(lesson - 5) - For Loops can be found at - https://steemit.com/programming/@robertlyon/java-programming-for-beginners-lesson-5-for-loops
In this lesson, I am going to elaborate on the work that I did on loops in the last section(for loops). This lesson will cover while loops and do while loops. These two loops will complement the work you have already done on for loops and give you more tools and choice to use depending on different situations you may come across in your programming career.
While Loops
What are they?
If you have looked at my last lesson on for loops then this lesson on while loops should be relatively easy for you to follow. While loops are similar to for in their syntax, although they do have a few differences that I will cover below. One of the main things to think about is that a for loop relies on us know how many times we want to loop through the loop and a while loop will run until a certain condition is met. Let us take a look at the code below and we can dissect it and look at the set up of a while loop.
Structure of a for loop
public class WhileLoops {
public static void main(String[] args)
{
boolean loopCondition = true;
int loopCounter = 0;
while(loopCondition)
{
if(loopCounter > 99)
{
System.out.println("The loop has reached 100");
loopCondition = false;
}
else
{
loopCounter++;
}
}
}
}
If we look at the program above we can immediately see a resemblance to the for loop, both loops have a condition that must be met and both loops have a code body.
Pay attention to the line numbers in the image as I will be using these to reference the line of code I am talking about.
So, on lines 4 and 5 I have declared 2 variables, 1 boolean on line 4 named loopCondition which I have set to true, this will be the condition that checks to see if the loop will continue. The second variable is an int named loopCounter. This will count how many times the loop has been performed and will become apparent in the main body of the loop.
The while loop starts on line 7 with while(loopCondition)
. The word "while" is the keyword that lets the compiler know that you want to start a while loop. It is the same idea as the "for" keyword we introduced in the last lesson, without these keywords the compiler doesn't know what we want.
Inside the parentheses the loops conditional statement is the variable loopCondition. This variable holds the value true. The condition for a while loop must be true for the loop to execute. If the condition is equal to false then the program will skip the loop and continue on with the program.
The block of code inside the loop contains an if/else statement. If you are unfamiliar with these then look back to my earlier lesson on IF statements to bring yourself up to speed.
So if we look at line 9 then we can see that the if statement checks to see whether the loopCounter variable is greater than 99. As it is currently at 0 the else statement on line 14 gets executed. This means that the value held within the variable loopCounter is incremented to by 1.
The loop now goes back to check it's condition(the variable loopCondition and as it is still equal to true the loop exectues again. The if statement is checked again to see if loopCounter is greater than 99. As it's value is 1 the else statement is executed again and the counter is incremented by 1.
This process will keep happening until the loopCounter variable holds the value 100. At this point the if statement will be executed and the println statement will be executed. Now, this is the important part, the variable loopCondition will be set to false. This means that when the loop goes back now to check its condition(loopCondition). It will now find that this is equal to false. When this happens the loop will end and the program can continue.
We will now move onto do while loops which are very similar but have one distinctively different feature.
Do while loops
What are they?
Do while loops do the same thing as while loops except for one difference. A while loops condition is checked at the start of the loop where as in a do while loop the condition is checked at the end of the loop. This means that a do while loop always executes the code in its body before it checks the condition.
Have a look at the code below then we will look into do while loops in a little bit more detail.
public class WhileLoops {
public static void main(String[] args)
{
boolean loopCondition = true;
int loopCounter = 0;
do
{
if(loopCounter > 99)
{
System.out.println("The loop has reached 100");
loopCondition = false;
}
else
{
loopCounter++;
}
} while (loopCondition);
}
}
I have purposely kept the code above as similar as possible to the example on while loops so that we can focus on the parts that have changed and you can compare the differences by yourself.
So as we can see on line 7 the keyword "do" appears. Like "while" and "for" this is the keyword that lets the compiler know that it is dealing with a do while loop.
What happens when a do while loop is executed is the code in the body of the loop is executed no matter what. So the if statement performs its check to see whether "loopCounter" is greater than 99. As it is 0, the else statement is executed and loopCounter is incremented by 1.
The fact that loopCounter has already been incremented by 1 is actually an important part to consider because in the while loop the condition was evaluated at the start when loopCounter held the value 0. Whereas in the do while loop, by the first time loopCounter is checked, the value it holds has already been incremented once. This is something you need to pay attention to and can lead to errors in your logic.
On line 18 you can see the familiar "while" keyword. This line works exactly the same as it did in the while loop and checks the condition to see if it is true. As it is true the loop executes again, this will keep on going until loopCounter is greater than 99 and the loopCondition variable is set to false. At this point, the loop will end and the program will carry on as normal.
Conclusion
In this lesson, I have covered both while loops and do while loops, although they are similar they can be used in for different things. I plan on doing a series on small programs for beginner programmers after I have covered the basics of the language which give a deeper understanding of the topics I am teaching. You should now be able to create your own while and do while loops. You should practice these on your own and get familiar with the syntax so that you can recall it from memory.
Next Lesson
In the next lesson, I will be covering methods.
If there is anything in this lesson that confuses you or there is anything programming related that you need help with then please comment below and I will try my best to help you.
As always if there are any improvements you think I can make to this post then please leave a comment and I will consider adding it.
Thank you for reading and I hope that someone will get some use out of these tutorials.
Message to readers
Thanks for taking the time to read my post, if you are interested in Science, Technology or Computer Science then check out my blog, content is a little sparse at the moment but I am making an effort to provide good quality original content to the Steemit community.
That is a very interesting post. I think it would be very useful, for the readers, to add extra references where more information could be found (there are plenty of them on the web ^^). In addition, I am fully convinced that this will bring you more rewards ;)
Thanks in advance for your consideration.
Listen to the guy! He knows what he is talking about!
lol ^^
Thanks for the feedback, I will definitely incorporate this into my future lessons :)
We are looking forward to it! :)
Do while loops are great especially for game development. You've got a fairly comprehensive tutorial here.
Thanks, yeah they are, I will be doing some more advanced tutorials in the future that covers stuff like game development after I cover the basics :).
@robertlyon , nice Java programming tutorial. big thumb up for you.
Thanks :)
[deleted]
Thanks, yeah I will try a few exercises in the next lesson. I was planning to do some lessons on building programs after I have covered the basics :), I will check out your tutorial
I am actually learning java in one of my computer classes right now, If I need any help I will definitely comeback. We are currently working on arrays.
Good work, i will be covering Arrays shortly, probably at the start of next week :)
Congratulations @robertlyon! You have completed some achievement on Steemit and have been rewarded with new badge(s) :
Award for the number of upvotes
Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here
If you no longer want to receive notifications, reply to this comment with the word
STOP