1 / 17

Loops: Repeating One or More Statements

Loops: Repeating One or More Statements. for loop while loop do-while loop break statement in a loop continue statement in a loop Nested loops. Loops. Iteration statements while (conditions) { statements; } do {statements;} while (conditions);

nbunn
Download Presentation

Loops: Repeating One or More Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Loops: Repeating One or More Statements • for loop • while loop • do-while loop • break statement in a loop • continue statement in a loop • Nested loops

  2. Loops • Iteration statements • while (conditions) { statements; } • do {statements;} while (conditions); • for ( initializing_expression; conditions; iteration_expression) { statements; }

  3. while loop do-while loop

  4. The while Loop

  5. while Loop while (condition) { statements; } • Program 5.1

  6. The do-while Loop do { statements; } while (conditions); • Program 5.2

  7. The for Loop

  8. for Flowchart

  9. for Loop for (initialization; conditions; iteration) { statements; } • Program 5.3

  10. Loops and Variable Scope • int i = 1; for (; i<=count; i++) sum +=1; • for (int i=1; i<=count; i++) sum +=1;

  11. Controlling a for Loop withFloating-points Values const double pi = 3.14159265; for (double radius=2.5; radius<=20.0; radius+=2.5) cout << “radius = “ << setw(12) << radius << “ area =“ << setw(12) << pi*radius *radius << endl; • Program 5.4, 5.5

  12. Multiple Initializations in A Loop Expression • for (initialized expressions; conditions; expressions) • E.g. • for (int j=0, k=2, product=1; k<count; j++, k++) • Program 5.6, 5.7

  13. The comma operator

  14. Nested Loop • Using a nested loop to generate multiplication talbes • Program 5.8

  15. continue Statement while (cin.get(ch)) { statement1; if (ch == ‘\n’) continue; statement2; } • Program 5.9

  16. Indefinite Loops • for (;;) { statements; } • while (true) { statements; } • Using the break statement to terminate the indefinite loop

  17. break Statement while (cin.get(ch)) { statement1; if (ch == ‘\n’) break; statement2; } statement3; • Program 5.10, 5.11

More Related