while loop Vs. for loop Vs. do while loop in Java programming language
Coding River
while loop Vs. for loop Vs. do while loop
Hi and welcome back to this channel, Today we are going to talk about the differences and similarities that exist among the three repetition control structures that we talked about in the previous videos
The first point to note here is that for loops are used to implement counter-countrolled loops and that is the reason why they are typically called counted or indexed for loops So, in reality, the for loop control structure functions the same way as the counter-controlled while loop
In order to prove that, let’s consider the following for and while loop
for (int score = 0 ; score less than 10 ; score++) { System.out.print(score + “ “); } System.out.println(“**********);
int score = 0; while (score less than 10) { System.out.print(score + “ “); score++; }
If you run each of these loop statements, you will get the same result in the console
Typically, when writing a program, if the number of iterations of the loop known or determined in advance, then programmers choose to use the for loop control structure instead of the while loop The while loop is usually used by programmers when they cannot determine in advance, the number of repetitions needed and it could be zero
Meanwhile, the do while loop is used when the programmer cannot determine in advance, the number of repetitions needed but it must be at least one
The next thing to talk about is that while and for loops are also called pretest loops, simply because they both have entry conditions. That means that their loop conditions are evaluated first, before executing the body of the loop. These loops might never activate in a program, especially when the loop condition evaluates to false right from the beginning
The do while loop, on the other hand is called a post-test loop, because it has an exit condition, therefore the body of the do while loop always executes at least once. The loop condition in a do while loop is evaluated only after executing the body of the loop
Consider the following while loop statement
int score = 10; while (score less than 10) { System.out.print(score + " "); score++; } System.out.println();
This while loop will give a completely different result from this do while loop int score = 10; do { System.out.print(score + " "); score++; } while (score less than 10); System.out.println();
The while loop will produce nothing Whereas the do while loop would output the number 10 and change the value of the variable score to 11
So guys, that was it for this video on repetition control structures
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 #forloop #whileloop ... https://www.youtube.com/watch?v=HkREZH1ywNo
11862365 Bytes