tailieunhanh - C++ Lab 7 Post-Test and ested Loops

So far we learned pre-test loops such as the general while loop, counter controlled loops specifically for loop, sentinel controlled loops and flag controlled loops. In all these loops we initialized the loop control variable(s) and tested the condition before entering the loop. For instance, data-validation would require the data to be read at least once and then test for its validity. There are special situations were the loop must be executed at least once before the testing is done. Two examples come to mind, a circular queue, and sorting. In such cases the post test looping construct is used | Lab 7 Post-Test and Nested Loops Dr. John P. Abraham So far we learned pre-test loops such as the general while loop counter controlled loops specifically for loop sentinel controlled loops and flag controlled loops. In all these loops we initialized the loop control variable s and tested the condition before entering the loop. For instance data-validation would require the data to be read at least once and then test for its validity. There are special situations were the loop must be executed at least once before the testing is done. Two examples come to mind a circular queue and sorting. In such cases the post test looping construct is used. There are also situations where it makes better reading when a post test loop is used. In such cases post test construct is not required. Do-While In C the post-test construct is implemented using do-while. In case of data-validation a do-while loop would look some thing like Do Prompt and read the data While the data is invalid keep reading the data if the data entered is not valid. Program 7-1_ include iostream using namespace std int main int monthNum do cout Enter the month a number ranging from 1 to 12 -- cin monthNum if monthNum 1 monthNum 12 cout Error month not in acceptable range n while monthNum 1 monthNum 12 return 0 Enter the month a number ranging from 1 to 12 -- 20 Error month not in acceptable range Enter the month a number ranging from 1 to 12 -- 13 Error month not in acceptable range Enter the month a number ranging from 1 to 12 -- 0 Error month not in acceptable range Enter the month a number ranging from 1 to 12 -- Nested Loops Here is a loop to display a multiplication table for the number 2. Program 7-2_ include iostream include iomanip using namespace std int main int tableFor 2 int multiplier 1 while multiplier 12 cout setw 3 tableFor x setw 3 multiplier setw 4 tableFor multiplier .

TỪ KHÓA LIÊN QUAN