In: Computer Science
This is for C++ Assuming the value of a is already defined elsewhere, convert the following code snippet from using a WHILE loop to using a DO-WHILE loop. Please paste in the modified code in the text area below.
int k = 1; while( k <= 8 ) { a = a * k; k++; }
The equivalent do-while() loop is given below:
do
{
if(k>8)
break;
a = a * k;
k++;
}
while(true);
The screenshot of the above source code is given below:
Types of loops:
1. Entry controlled loops:
The loop which checks for the exit condition before each iteration is known as entry controlled loops.
For example:
while(condition)
{
//statements
}
The while loop will be executed until the condition is true and will exit when the condition will be false.
This loop should be used when we don't know the number of iteration in advance but a condition is defined and the required statement must not execute for a single time if the condition is false.
2. Exit controlled loops:
The loop which checks for the exit condition after each iteration is known as exit controlled loops.
For example:
do
{
//statements
} while(condition)
The do-while loop will be executed until the condition is true and will exit when the condition will be false.
This loop should be used when we don't know the number of iteration in advance but a condition is defined and the required statement must execute at least once even if the condition is false.