Entry vs Exit Controlled Loops
Entry controlled vs Exit controlled Loops
An entry controlled loop is a loop in which the condition for executing the loop is checked at the beginning of the loop, before the code inside the loop is executed.
for
loop,while
loop are entry controlled loop as they check the condition first before executing the code inside.An exit controlled loop is a loop in which the condition for executing the loop is checked at the end of the loop, after the code inside the loop has been executed. The
do-while
loop is an example of an exit controlled loop, because the condition for executing the loop is checked after the code inside the loop has been executed.
Entry-controlled and Exit-controlled are not terms you will find officially in C documentation or books, These term are used to illustrate an idea and make an understanding of how the loop's control flow works
Examples of entry controlled loops
- A
for
loop that iterates 10 times:
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++)
{
printf("Iteration %d\n", i + 1);
}
return 0;
}
Output:
- A
while
loop that continues to execute while the value of a variablex
is less than 5:
#include <stdio.h>
int main()
{
int x = 0;
while (x < 5)
{
printf("x is currently %d\n", x);
x++;
}
return 0;
}
Output:
- A
for
loop that iterates over an array and prints out each element:
#include <stdio.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Output:
Examples of exit controlled loops
- A
do-while
loop that repeatedly asks the user to enter a number, and exits only when the user enters a negative number:
#include <stdio.h>
int main() {
int num;
do {
printf("Enter a number: ");
scanf("%d", &num);
if (num >= 0) {
printf("You entered %d\n", num);
}
} while (num >= 0);
return 0;
}
- A
do-while
loop that keeps running until user enter 'y' or 'Y' for exit
#include <stdio.h>
int main() {
char choice;
do {
// code to be executed
printf("Do you want to exit? (y/n) ");
scanf(" %c", &choice);
} while (choice != 'y' && choice != 'Y');
return 0;
}
- A
do-while
loop that continues to execute as long as a variablex
is less than or equal to 3:
#include <stdio.h>
int main()
{
int x = 0;
do
{
printf("x is currently %d\n", x);
x++;
}
while (x <= 3);
return 0;
}
Output: