Counter-controlled while loop statements - JAVA tutorial with PRACTICAL example смотреть онлайн
Counter-controlled while loops
Hi and welcome back to this channel
Today, I would like to talk to you about Counter-controlled while loops
Actually, in Java programming, the while loop can take various forms
In this video, I will show how to use the counter-controlled while loop
This counter-controlled while loop is used when you know exactly how many times your while loop action statements need to be executed.
For example, if you want to create a program in which a set of statements need to execute a specific number of times.
You can then set a counter that will be used to control or track how many times the action statement is executed.
Let’s use the example on the screen illustrate
int counter = 0
while (counter less than 10) {
System.out.println(“The output statement is executed ” + counter + “ times”);
counter ++;
}
This portion of code is a typical example of a counter-controlled while loop
We have started by setting up and initializing a counter variable that will be used to track the number of times the action statement will be executed
Next, we have the loop condition that is used to test the counter variable or the loop control variable
The number 10 here, represents the number of times the action statement needs to execute
If the value of the variable counter is less than 10, the statements in the body of the while loop execute.
The loop will continue to execute until the value of the counter is greater than or equal to 10
In the body of the while statement, the action statements are executed as long as the loop condition is true
Also, the value of the variable counter is incremented and updated as long as the loop condition is true
Let’s take another example that will be a bit more complex and allow us to understand how to use the counter-controlled while loop
In this example, we are going to create a program that will calculate the summation and the average of numbers entered by the user in our program
We will use some of the concepts we saw in the previous videos as well
Since we want the program to prompt the user to enter data using the keyboard
So we need to add an input object
public class CounterControlledWhileLoop
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Next, we have to declare the various variables that will be used in the program
The first one will be a variable that will store the numbers entered by the user
int number;
Second, the variable that will hold the summation and the average
int sum, average;
Next, we will declare a variable that will limit the number of integer values the user will be authorized to enter
int limit;
Finally, since we will use a counter-controlled while loop in this program
Let’s declare a counter
int counter;
After declaring the variables, I will write an output statement that prompts the user to input data in the program
System.out.print("Please enter the number that will be used as the limit");
The next statement must allow the user to enter an integer value from his keyboard
limit = console.nextInt();
The value entered will be stored in the variable limit
System.out.println();
The next portion of code to write is the while loop statement
But before that, we have to initialize the various variables that will be used in the while statement, here the variable sum and counter
sum = 0;
counter = 0;
Let’s also add an output statement that would prompt the user to enter the values
System.out.println("Great ! You can now type in " + limit + “ integer numbers”);
Now, we can write the while loop statement
In which, the condition would check whether the counter is less than the value stored on the variable limit
while (counter less than limit) (Note that, the counter here, determines how many time input values have been read)
{
If the condition is met
Here are the action statements to execute
The first will be an input statement that will allow the user to input the numbers
number = console.nextInt();
The second statement will operate the sum of the numbers entered by the user
sum = sum + number;
The third statement will be used to increment the variable counter
counter++;
}
Outside of the while loop, let’s output the result of the summation of all the input numbers
System.out.println("The summation of all the numbers is equal to “ + sum);
We can also add an if statement
That will allow us to print a message in case there is no input in the program
if (counter != 0) {
Average = sum / couter;
System.out.println("The average of all the numbers is " + average);
}
else {
System.out.println("There was no input.");
}
So, once everything is set up correctly
You can now run your program
That’s it about the counter-controlled while loop, the next video I will talk about another form of while loop structure, that is the Sentinel-controlled while loop
#codingriver
#java tutorial
#java programing
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Counter-controlled while loop statements - JAVA tutorial with PRACTICAL example» бесплатно и без регистрации, вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.