Unlike for and while loops, which test the loop condition at the top of the loop, the
do-while loop checks its condition at the bottom of the loop. This means that a
do-while loop always executes at least once. The general form of the do-while loop is
do{
statement;
} while(condition);
do-while loop checks its condition at the bottom of the loop. This means that a
do-while loop always executes at least once. The general form of the do-while loop is
do{
statement;
} while(condition);
Although the curly braces are not necessary when only one statement is present, they
are usually used to avoid confusion (to you, not the compiler) with the while. The
do-while loop iterates until condition becomes false.
The following do-while loop will read numbers from the keyboard until it finds a
number less than or equal to 100.
do {
scanf("%d", &num);
} while(num > 100);
Perhaps the most common use of the do-while loop is in a menu selection function.
When the user enters a valid response, it is returned as the value of the function.
Invalid responses cause a reprompt. The following code shows an improved version of
the spelling-checker menu developed earlier in this chapter:
void menu(void)
{
char ch;
printf("1. Check Spelling\n");
printf("2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf(" Enter your choice: ");
do {
ch = getchar(); /* read the selection from
the keyboard */
switch(ch) {
case '1':
check_spelling();
break;
case '2':
correct_errors();
break;
case '3':
display_errors();
break;
}
} while(ch!='1' && ch!='2' && ch!='3');
}
are usually used to avoid confusion (to you, not the compiler) with the while. The
do-while loop iterates until condition becomes false.
The following do-while loop will read numbers from the keyboard until it finds a
number less than or equal to 100.
do {
scanf("%d", &num);
} while(num > 100);
Perhaps the most common use of the do-while loop is in a menu selection function.
When the user enters a valid response, it is returned as the value of the function.
Invalid responses cause a reprompt. The following code shows an improved version of
the spelling-checker menu developed earlier in this chapter:
void menu(void)
{
char ch;
printf("1. Check Spelling\n");
printf("2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf(" Enter your choice: ");
do {
ch = getchar(); /* read the selection from
the keyboard */
switch(ch) {
case '1':
check_spelling();
break;
case '2':
correct_errors();
break;
case '3':
display_errors();
break;
}
} while(ch!='1' && ch!='2' && ch!='3');
}
Here, the do-while loop is a good choice because you will always want a menu
function to execute at least once. After the options have been displayed, the program
will loop until a valid option is selected.
function to execute at least once. After the options have been displayed, the program
will loop until a valid option is selected.
No comments:
Post a Comment