If we want to print from 0, then assign the value 0 during initialization. After that, the loop will be terminated, and control will fall outside the loop.
In the body of a loop, we have a print function to print our number and an increment operator to increment the value per execution of a loop. An initial value of num is 1, after the execution, it will become 2, and during the next execution, it will become 3. This process will continue until the value becomes 4, and then it will print the series on the console and terminate the loop. In the above example, we have printed a multiplication table of 2 using a do-while loop.
Then we have written a do-while loop. In a loop, we have a print function that will print the series by multiplying the value of num with 2. After each increment, the value of num will increase by 1, and it will be printed on the screen. Initially, the value of num is 1. Hence the value 2 will be printed. This will go on until the value of num becomes Next, the loop will be terminated, and a statement which is immediately after the loop will be executed.
In this case, it will return 0. When checking a condition, if the first iteration is compulsory, we need to use the while loop. It can also be used if the number of iterations is unknown or uncertain. We have used another one System.
We are going to make the condition false. From the above code, it is clear that the condition is false. But it will still execute the statement once because the condition is tested after the execution of the statements. The process repeats until the condition becomes false. Unlike the while loop which tests the condition before the code within the block is executed, the do-while loop is an exit-condition loop, in the sense that, the code must always be executed first and then the expression or test condition examined.
If it is true, the code executes the body of the loop again. If the expression is false, the loop terminates and control transfers to the statement following the do-while loop. Viva Differences. What Are Loops? Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Asked 7 years, 11 months ago. Active 4 years, 3 months ago. Viewed 11k times. Improve this question.
The difference is when the condition check occurs, of course. In a do-while, the body is always executed at least once. Otherwise, there really is nothing to say. And NO , what you mentioned is not the right way to interchange the loop, while having the functionality intact.
Thank you for explaining this so quickly guys, much appreciated. Add a comment.
0コメント