Do while loop repetition control structure - Java tutorial for beginners
do while loop repetition control structure - Java tutorial for beginners
In this video, we are going to talk about the third type of repetition control structure which is the do while loop
Here is a typical example of how a do while loop statement looks like
int score = 0;
do {
System.out.print(score + “ “);
score++;
}
while (score less than 10);
Let me now explain the various elements in this statement
First, do, here is a reserved word in Java and it is telling us that this particular statement is a do while loop
After the keyword, do, we get the action statements
These action statements can be a simple statement, having just one statement like this
Or, it can be a compound statement which is made up of more than one action statement
Always make sure to surround with curly braces in case of compound action statement
Next, there is another reserved word while
Then, the following expression is called the loop condition
You can notice that in this loop statement the action statement comes before the condition
That means that during the execution, the action statement executes first
And then the loop condition is evaluated right after.
If the loop condition evaluates to true, then the action statement will execute again
As long as the loop condition evaluates to true, then the action statement will continue to execute
So, in order to avoid an infinite loop, you have to make sure that the body of the loop contains a statement that would make the loop condition evaluate to false at a certain point of the execution
That’s the reason why we put the statement score++
See, if we remove that statement score++ from the code
And run, there we are going to get an infinite loop
Let me put the statement score++ back
And run
There, we have the result in the console
The do while loop is somehow different from the while loop or the for loop
In the while and for loops, the loop condition is evaluated first before the action statement
So, these loops might never activate at all
Especially, in the cases where the condition evaluates to false right from the entry point of the loop
Consider this while loop
int score = 10;
while (score less than 10)
{
System.out.print(score + " ");
score++;
}
System.out.println();
Run this while loop and notice that it produces nothing
This is because, the entry condition evaluates to false right at the beginning
So, the while loop will not activate at all
You either need to adjust the condition or the value stored in the variable score
Meanwhile, in the do while loop, the condition is evaluated after the action statement
That means that the body of the loop always executes at least once
Even if the condition is false at the beginning of the execution
Consider this do while loop
int score = 10;
do
{
System.out.print(score + " ");
score++;
}
while (score less than 10);
System.out.println();
Run this portion of code
Notice that it returns the number 10 and it also increments the value of score to 11
So guys, that’s it about do while looping structure
Thanks for watching and I hope it was informative.
Please do not forget to like and SUBSCRIBE to this channel for more.
Let’s meet in the next video.
#codingriver
#javatutorial
#javacourse
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Do while loop repetition control structure - Java tutorial for beginners», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.