中国高校课件下载中心 》 教学资源 》 大学文库

英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 8 - Looping

文档信息
资源类别:文库
文档格式:PDF
文档页数:3
文件大小:109.89KB
团购合买:点击进入团购
内容简介
英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 8 - Looping
刷新页面文档预览

4Lecture 8Looping:nedat.Lastlecturewesawhowwecouldfollowdifferentpathsthroughaprogramusingdecisions.Thistimewewill lookat repeatingsectionsof.codeseveraltimes.Chas3typesofloop-while loops-do..while loopsbattrd-forloopsFileDaa SnuctueCeseygeowhile loopwhile loopwhile(expr)while(expr)(.e.g.,while(hungry)statement,statenenteat_sandwich();//More lines// of code.Ifyournothungryyoueatzerosandwiches1?Aswiththe if statement, exprcanbetruewhile.c(non-zero)orfalse (zero)...:Iftrue,statementisexecuted.Thiscanbeablockofstatementsenclosedinbraces()?NOTE:thestatementcouldbeexecutedzerotimesdo...while loopstatemeldo...while loopdostatement;// More statements if you likedowhile.cwinclude catdio.hsJ while (expr),sain():Againmultiplestatementscanbe included innt nthe ()do (.Notethatstatement is executedat least onceto fininh):"),Puts(-scanf (-ti-,sn):e.g..printt("rou mmtered tilmln", m);In this case you havedovhile (m) to take the test once,take_driving_test(;maybe more times,)while (ipassed);until youpass

1 1. Introduction 2. Binary Representation 3. Hardware and Software 4. High Level Languages 5. Standard input and output 6. Operators, expression and statements 7. Making Decisions 8. Looping 9. Arrays 10. Basics of pointers 11. Strings 12. Basics of functions 13. More about functions 14. Files 14. Data Structures 16. Case study: lottery number generator Lecture 8 Lecture 8 Looping • Last lecture we saw how we could follow different paths through a program using decisions. • This time we will look at repeating sections of code several times • C has 3 types of loop – while loops – do.while loops – for loops while loop • As with the if statement, expr can be true (non-zero) or false (zero). • If true, statement is executed. This can be a block of statements enclosed in braces { } • NOTE: the statement could be executed zero times expr statement F T while(expr) statement; while(expr){ statement; // More lines // of code } while loop • e.g., while(hungry) eat_sandwich(); • If your not hungry you eat zero sandwiches /* Example: while loop */ #include main() { int m = 0, n; puts("Enter a small integer (e.g. 10): "); scanf("%i", &n); while (m main() { int m; do { puts("Enter an integer (0 to finish):"); scanf("%i", &m); printf("You entered %i\n\n", m); } while (m); puts("Finished"); } /* Example: do-while loop */ #include main() { int m; do { puts("Enter an integer (0 to finish):"); scanf("%i", &m); printf("You entered %i\n\n", m); } while (m); puts("Finished"); } dowhile.c dowhile.c

for.cforloopDfor(expr1;expr2;expr3)statement:forcomma.cAgain thestatement can bea blockTheforloopisthemostflexibletypeofloop:It ismostoftenusedwhenyouwanttodosomethingntimes e.g.aefor(int i=0;i<n;i++)do_something;initialisation.1aconditionalexpressionexpressionraexpression..You can create any type of loop from a for loop plusachievesomeotherusefulfunctions ifyourcreativeNestedforloops:We've seen nested if statements, its also verycommontoseenestedforloops8RR988988g1NHAHORES58333991#9S#SR23309381NRHOENHRERTRSRRRRR903.r1.0continue,breakandgotobreak.cBadprogrammingpracticeSometimeswewantto jumptotheendofaloopfor all 3types we can do thiswith continue;Often we want to leave a loop earlyfor all 3 types we can do thiswith breakOne common programming technique is to constructan infinite loop (one that does not terminate) but jumpoutof itusingabreakstatementcontinue.cC also includes a goto statement but Iam notgoing:to explain how to use it, its bad practice and shouldn'thave been included in the programming language (inmy opinion).I have neverused goto in eitheraC or C++programand that'smanyhundredsofthousandsoflinesofcod2

2 for loop for(expr1;expr2;expr3) statement; • Again the statement can be a block • The for loop is the most flexible type of loop. • It is most often used when you want to do something n times e.g., for(int i=0;i #define skip {putchar('\n'); putchar('\n');} /* This is called a "macro" */ main() { int m, i, n = 20; /* Standard C idiom for doing something n times: */ for (i = 0; i 0; m-) /* counting down */ printf("%i ", m); skip; for (m = 0; m #define skip {putchar('\n'); putchar('\n');} /* This is called a "macro" */ main() { int m, i, n = 20; /* Standard C idiom for doing something n times: */ for (i = 0; i 0; m-) /* counting down */ printf("%i ", m); skip; for (m = 0; m main() { int i, j; for (i = 0, j = 9; i main() { int i, j; for (i = 0, j = 9; i main() { int row; /* Row index */ int col; /* Column index */ puts("200 X's:\n"); for (row = 0; row main() { int row; /* Row index */ int col; /* Column index */ puts("200 X's:\n"); for (row = 0; row main() { int s; puts("Infinite for loop:"); for ( ; ; ) { printf("Enter an integer (999 to finish): "); scanf("%i", &s); if (s == 999) break; } puts("Loop exited\n"); puts("Infinite while loop:"); while (1) { printf("Enter an integer (999 to finish): "); scanf("%i", &s); if (s == 999) break; } puts("Loop exited\n"); puts("Infinite do-while loop:"); do { printf("Enter an integer (999 to finish): "); scanf("%i", &s); if (s == 999) break; } while (1); puts("Loop exited\n"); } /* Example: exiting loops using break */ #include main() { int s; puts("Infinite for loop:"); for ( ; ; ) { printf("Enter an integer (999 to finish): "); scanf("%i", &s); if (s == 999) break; } puts("Loop exited\n"); puts("Infinite while loop:"); while (1) { printf("Enter an integer (999 to finish): "); scanf("%i", &s); if (s == 999) break; } puts("Loop exited\n"); puts("Infinite do-while loop:"); do { printf("Enter an integer (999 to finish): "); scanf("%i", &s); if (s == 999) break; } while (1); puts("Loop exited\n"); } /* Example: skipping to end of loops using continue */ #include main() { int h = 500, count = 0; printf("All the numbers from %i to zero\n", h); puts("not divisible by 2, 3, 5 or 7:\n"); do { if (h % 2 == 0) /* skip those divisible by 2 */ continue; if (h % 3 == 0) /* . by 3 */ continue; if (h % 5 == 0) /* . by 5 */ continue; if (h % 7 == 0) /* . by 7 */ continue; printf("%5i", h), count++; if (count % 10 == 0) /* print 10 per line */ putchar('\n'); } while (h-); } /* Example: skipping to end of loops using continue */ #include main() { int h = 500, count = 0; printf("All the numbers from %i to zero\n", h); puts("not divisible by 2, 3, 5 or 7:\n"); do { if (h % 2 == 0) /* skip those divisible by 2 */ continue; if (h % 3 == 0) /* . by 3 */ continue; if (h % 5 == 0) /* . by 5 */ continue; if (h % 7 == 0) /* . by 7 */ continue; printf("%5i", h), count++; if (count % 10 == 0) /* print 10 per line */ putchar('\n'); } while (h-); } continue.c continue.c break.c break.c

Menu Example.You nowknowenoughCto write some realnDlife programs. As an example here is aSTEQprogram which provides a menu system2A/, 10o3国11954souads0:m福:n“,ne*0性 Tuw uene arm..1408 012*aimeku1AmPtuTPR9.n.emsn9.8ar./itwaeuynh1omU.wwredkaeum.eo0)山福1RUi11 op3

3 Menu Example • You now know enough C to write some real life programs. As an example here is a program which provides a menu system McDUCK'S ELECTRONIC MENU SYSTEM =============================== Smile at customer; "How may I help you?" [B]ig Duck - press B (then Enter) [H]amburger - press H (then Enter) [C]heeseburger - press C (then Enter) [F]ries - press F (then Enter) [L]arge fries - press L (then Enter) [S]oft drink - press S (then Enter) [A]pple pie - press A (then Enter) [M]ilk shake - press M (then Enter) Press [X] (then Enter) when order is complete McDUCK'S ELECTRONIC MENU SYSTEM =============================== Smile at customer; "How may I help you?" [B]ig Duck - press B (then Enter) [H]amburger - press H (then Enter) [C]heeseburger - press C (then Enter) [F]ries - press F (then Enter) [L]arge fries - press L (then Enter) [S]oft drink - press S (then Enter) [A]pple pie - press A (then Enter) [M]ilk shake - press M (then Enter) Press [X] (then Enter) when order is complete b Big Duck $2.50 l Large fries $0.75 s Soft drink $0.50 x Order complete - 3 items - total $3.75 "Thank you! That'll be $3.75" Take money, give change "Thank you!" Fetch 3 items "Thanks for eating at McDuck's! Enjoy your meal!" b Big Duck $2.50 l Large fries $0.75 s Soft drink $0.50 x Order complete - 3 items - total $3.75 "Thank you! That'll be $3.75" Take money, give change "Thank you!" Fetch 3 items "Thanks for eating at McDuck's! Enjoy your meal!" /* Example: menu system, using do.while, getchar and switch */ /* You've reached a point in the course where you know enough C to start writing real programs. Here's a fairly realistic example: a menu ordering system. It could be improved - for instance there's no way to cancel an item. Also, when we get on to functions, the structure could be made more modular. Nevertheless, it works! */ #include #define BIG 2.50 /* price of Big Duck */ #define HAM 2.00 /* price of hamburger */ #define CHE 2.00 /* price of cheeseburger */ #define FRI 0.50 /* price of fries */ #define LAR 0.75 /* price of large fries */ #define SOF 0.50 /* price of soft drink */ #define APP 1.00 /* price of apple pie */ #define MIL 0.75 /* price of milk shake */ int main(void) { char key; /* key pressed */ int items = 0; /* number of food items */ int done = 0; /* order complete? */ float total = 0.00; /* total price */ /* Output information: */ puts("McDUCK'S ELECTRONIC MENU SYSTEM"); puts("===============================\n"); puts("Smile at customer; \"How may I help you?\"\n"); puts(" [B]ig Duck - press B (then Enter)"); puts(" [H]amburger - press H (then Enter)"); puts(" [C]heeseburger - press C (then Enter)"); puts(" [F]ries - press F (then Enter)"); puts(" [L]arge fries - press L (then Enter)"); puts(" [S]oft drink - press S (then Enter)"); puts(" [A]pple pie - press A (then Enter)"); puts(" [M]ilk shake - press M (then Enter)\n"); puts("Press [X] (then Enter) when order is complete\n"); /* Example: menu system, using do.while, getchar and switch */ /* You've reached a point in the course where you know enough C to start writing real programs. Here's a fairly realistic example: a menu ordering system. It could be improved - for instance there's no way to cancel an item. Also, when we get on to functions, the structure could be made more modular. Nevertheless, it works! */ #include #define BIG 2.50 /* price of Big Duck */ #define HAM 2.00 /* price of hamburger */ #define CHE 2.00 /* price of cheeseburger */ #define FRI 0.50 /* price of fries */ #define LAR 0.75 /* price of large fries */ #define SOF 0.50 /* price of soft drink */ #define APP 1.00 /* price of apple pie */ #define MIL 0.75 /* price of milk shake */ int main(void) { char key; /* key pressed */ int items = 0; /* number of food items */ int done = 0; /* order complete? */ float total = 0.00; /* total price */ /* Output information: */ puts("McDUCK'S ELECTRONIC MENU SYSTEM"); puts("===============================\n"); puts("Smile at customer; \"How may I help you?\"\n"); puts(" [B]ig Duck - press B (then Enter)"); puts(" [H]amburger - press H (then Enter)"); puts(" [C]heeseburger - press C (then Enter)"); puts(" [F]ries - press F (then Enter)"); puts(" [L]arge fries - press L (then Enter)"); puts(" [S]oft drink - press S (then Enter)"); puts(" [A]pple pie - press A (then Enter)"); puts(" [M]ilk shake - press M (then Enter)\n"); puts("Press [X] (then Enter) when order is complete\n"); /* Handle key presses: */ do { fflush(stdin); /* flush keyboard buffer */ key = getchar(); /* read key */ switch (key) { case 'B': case 'b': printf(" Big Duck $%4.2f\n", BIG); items++; total += BIG; break; case 'H': case 'h': printf(" Hamburger $%4.2f\n", HAM); items++; total += HAM; break; case 'C': case 'c': printf(" Cheeseburger $%4.2f\n", CHE); items++; total += CHE; break; case 'F': case 'f': printf(" Fries $%4.2f\n", FRI); items++; total += FRI; break; case 'L': case 'l': printf(" Large fries $%4.2f\n", LAR); items++; total += LAR; break; case 'S': case 's': printf(" Soft drink $%4.2f\n", SOF); items++; total += SOF; break; case 'A': case 'a': printf(" Apple pie $%4.2f\n", APP); items++; total += APP; break; /* Handle key presses: */ do { fflush(stdin); /* flush keyboard buffer */ key = getchar(); /* read key */ switch (key) { case 'B': case 'b': printf(" Big Duck $%4.2f\n", BIG); items++; total += BIG; break; case 'H': case 'h': printf(" Hamburger $%4.2f\n", HAM); items++; total += HAM; break; case 'C': case 'c': printf(" Cheeseburger $%4.2f\n", CHE); items++; total += CHE; break; case 'F': case 'f': printf(" Fries $%4.2f\n", FRI); items++; total += FRI; break; case 'L': case 'l': printf(" Large fries $%4.2f\n", LAR); items++; total += LAR; break; case 'S': case 's': printf(" Soft drink $%4.2f\n", SOF); items++; total += SOF; break; case 'A': case 'a': printf(" Apple pie $%4.2f\n", APP); items++; total += APP; break; case 'M': case 'm': printf(" Milk shake $%4.2f\n", MIL); items++; total += MIL; break; case 'X': case 'x': printf("\nOrder complete - "); printf("%i items - total $%4.2f\n", items, total); done = 1; break; default: puts(" Invalid key! Try again."); break; } } while (!done); /* Output information: */ printf("\n\"Thank you! That'll be $%4.2f\"\n", total); puts("Take money, give change"); puts("\"Thank you!\"\n"); printf("\nFetch %i items\n", items); puts("\"Thanks for eating at McDuck's! Enjoy your meal!\""); } case 'M': case 'm': printf(" Milk shake $%4.2f\n", MIL); items++; total += MIL; break; case 'X': case 'x': printf("\nOrder complete - "); printf("%i items - total $%4.2f\n", items, total); done = 1; break; default: puts(" Invalid key! Try again."); break; } } while (!done); /* Output information: */ printf("\n\"Thank you! That'll be $%4.2f\"\n", total); puts("Take money, give change"); puts("\"Thank you!\"\n"); printf("\nFetch %i items\n", items); puts("\"Thanks for eating at McDuck's! Enjoy your meal!\""); }

已到末页,全文结束
刷新页面下载完整文档
VIP每日下载上限内不扣除下载券和下载次数;
按次数下载不扣除下载券;
注册用户24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
相关文档