What are Loops in Java? And What are the Different Types of Loops?

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

To begin with, let’s figure out what a loop is. A loop is any repeating action.

For example, every morning, you:

  1. get up
  2. go to the bathroom, brush your teeth, and shave your face or legs
  3. open the fridge and eat everything at hand
  4. get dressed
  5. go to work or college

So, at least 5 times a week (Monday-Friday), you perform the same sequence of actions. And if the sequence of actions is the same, then we are talking about a loop. So now you know what a loop is.

In Java, there are 4 loop types:

  1. the "while" loop
  2. the "do…while" loop
  3. the "for" loop
  4. the "for each" loop

At this stage, it will be enough for you to know only the first three loop types.

We will take a look at the "for each" loop a little bit later in another article. For now, all you need to know is that the "for each" loop is a variation of the "for" loop. The "for each" loop only appeared for the first time in JDK5. In earlier versions of JDK, it didn’t exist.

So it’s high time to learn about the "while" loop.

The While Loop

This loop is sometimes called the "as long as” loop.

1
Let’s start with a somewhat funny, fictional everyday example.

Let’s say you have a friend called Charlie and he has a girlfriend called Katie. They are in the “rose and candy stage” - you know what that means. Charlie gives her flowers, invites her to restaurants, and buys her ice cream. In short, he's romancing her.

But Charlie has a limited budget. So he tells himself: “I will invite Katie to restaurants and give her flowers as long as I have at least $10 in my wallet. But as soon as I see that I have less than $10, it will all be over; we will conclude the “rose and candy stage” and, instead, we will just sit on the couch at home and watch TV and so on."

If you describe this life situation using the while loop (remember, sometimes the while loop is called the “as long as” loop), it will look as follows:

 

 

In the example above:

  1. While is "as long as"
  2. (in the wallet > = 10$) is the condition
  3. “buy ice cream for girlfriend”, “give flowers” – these are the actions which will be performed as long as the condition is true.

So, the general form of a while loop in Java looks as follows:

Remember, the essence of the while statement is that it repeats the action(s) as long as the condition is true. That means, as long as Charlie has > = 10$, he will buy ice ice cream for his girlfriend and give her flowers. When the condition Charlie has > = 10$ becomes false, the repetition of the actions “buy ice ice cream for girlfriend” and “give her flowers” will stop and the loop will be completed.

It’s time to try to write a Java code using the while loop.

Task No. 1

It’s necessary to display the numbers from 1 through 7, i.e. we should see the following on the screen: 1 2 3 4 5 6 7

Solution:

Task No. 2

But if we write the code this way, it won't be performed.

Why? Because the initial value is "int i =1", but we wrote "while (i <o)" in the condition. The i variable already equals 1, and therefore i can't be less than 0. Consequently, the code can't be executed even once.

Task No. 3

And if we wrote the code in the following way, the list of numbers would go on infinitely (1 2 3 4 5 6 7 …)

This is an example of a so-called infinite loop, because the numbers will be displayed to infinity *1 2 3 4 5 6 7 8 9 10 11 12 13 …) If you already ran this code on your computer, then you noticed that the program was blocked by the infinite loop, because the code wouldn’t stop; instead it would just continue displaying numbers on the screen. To get out of such a situation, you need to press the keyboard shortcut Alt + F4.

Why are the numbers displayed to infinity? Well, because we wrote "while (true)" in the code. And since the condition will always be true, the numbers will display endlessly.

Task No. 4

It’s necessary to display the following number sequence on the screen:

100 90 80 70 60 50 40 30 20 10

Solution:

Commentary on the task:

"i-=10;" is shorthand for "i = (i-10);"

Here you can find more examples of while loop tasks.

Do…while loop

The do…while loop is one of the variations of the while loop. To understand the difference between do…while and while loops, let’s compare two examples of code.

Task No. 5 – code with the while loop

Commentary: this code won’t be executed. This is because the condition "while ( i < 0 )" is checked, and the code executes only if the condition is true. i.e. the while loop pre-checks the condition.

Task No. 6 – code with the do…while loop

Commentary: At first, the while loop checks the condition and then executes the code (the body of the loop). On the other hand, the do…while loop first executes the body of the loop and then checks the condition. That’s why the loop body executes the code at least once. First, the actions are specified and the condition "while ( i < o)" is carried out and, only after that, does it check it the condition. In short, the number 2 will be displayed on the screen. And only after this happens is the "while ( i < 0)" checked, because the "2 > 0" loop will be completed. In other words, the "do…while" loop pre-checks the condition.

The general form of the "do…while" loop is as follows:

Remember: the "do…while" loop always executes at least once. We saw this clearly in the example above.

The "do…while" loop is a very good and convenient choice when you need to execute some action at least once or, under certain circumstances, when an action needs to be repeated several times.

The "For" loop

The "for loop" is also called the loop “with the counter”.

Let’s say we want to display the following message on the screen:

Awesome!

Awesome!

Awesome!

Awesome!

As you can see, the word “Awesome!” repeats four times. It’s obvious that you need to use a loop, because the same operation is repeated four times:

1. First, we displayed the wordAwesome! on the screen.

2. Second, we displayed the word Awesome! on the screen.

3. Third, we displayed the word Awesome! on the screen.

4. Fourth, we again displayed the wordAwesome! on the screen.

Note: If you know in advance how many times you want the same action to repeat, then you need to use the "for" loop. For instance, in the example above we knew we needed to display the word “Awesome!” four times. So we used the "for" loop.

Let’s look at this code step by step:

The construction "for (int i =1; i <=5; i++)" in the Java language is like saying “repeat so many times”. In our case: “Repeat from 1 to 5, that is 5 times”.

"int i = 1" is the first attribute and it is responsible for the definition of the initial value. This attribute is called initialization, where "i" is the loop variable.

"i <=5" is the second attribute and it is responsible for the condition under which the loop is executed i.e. the loop will be executed as long as the condition (i.e. the variable "i") doesn’t equal 5.

"i++" is the third attribute and it is responsible for changing the variable "i" after each step of the loop. Our example indicated “i++”, which means that the variable will be increased by one in each step of the loop – from 1 to 2, from 2 to 3, from 3 to 4, and from 4 to 5. This third attribute is called iteration.

The general form of the "for" loop in Java is as follows:

We suggest that you solve one more task.

Task No. 7

It is necessary to display the numbers from 3 to -3 at the screen i.e. the following numbers should appear on the screen: 3 2 1 0 -1 -2 -3

Solution:

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Facebooktwittergoogle_plustumblrFacebooktwittergoogle_plustumblr

Leave a Reply

Your email address will not be published.

Самоучители--узнать детальнее--