英格兰萨里大学:《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!\""); }
按次数下载不扣除下载券;
注册用户24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 7 - Making Decisions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 6 - Operators, Expressions and Statements.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 5 - Standard IO.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 4 - Simple Data Types.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 2 - Binary Representation.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 1 - Introduction.pdf
- 《计算机程序设计基础》课程学习指南(C语言)给C语言初学者的学习建议.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言初学者编程规范-2/2.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言初学者编程规范-1/2.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见问题详解.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见英文单词.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见错误中英文对照表.pdf
- 《计算机程序设计基础》课程教学大纲 C Programming Language(C语言).pdf
- 《计算机控制系统》课程教学资源(PPT课件)第7章 计算机控制系统设计与实现.ppt
- 《计算机控制系统》课程教学资源(PPT课件)第6章 分布式测控网络技术.ppt
- 《计算机控制系统》课程教学资源(PPT课件)第5章 计算机控制系统软件设计相关技术.ppt
- 《计算机控制系统》课程教学资源(PPT课件)第4章 先进控制技术.ppt
- 《计算机控制系统》课程教学资源(PPT课件)第3章 常规数字控制技术.ppt
- 《计算机控制系统》课程教学资源(PPT课件)第2章 计算机控制系统硬件设计相关技术.ppt
- 《计算机控制系统》课程教学资源(PPT课件)第1章 计算机控制系统概述.ppt
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 3 - Hardware and Software.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 9 - Arrays.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 10 - Basics of Pointers.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 11 - Strings.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 12 - Basics of Functions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 13 - More functions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 14 - Files.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 15 - Data Structures.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第1章 C语言概述.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第2章 基本数据类型和运算符.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第3章 控制结构.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第4章 数组和指针.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第5章 模块化编程.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第6章 指针进阶与内存空间管理.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第7章 结构体与共同体.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第8章 数据文件编程方法.pdf
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-10 IO函数值和注释语句.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-8 标识符和关键字.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-11 编程风格与常见错误.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-9 输入输出函数.ppt