A B C D E F B C D E F C D E F D E F E F F Nested for loop Example Cont

A b c d e f b c d e f c d e f d e f e f f nested for

This preview shows page 52 - 57 out of 57 pages.

A B C D E F B C D E F C D E F D E F E F F
Image of page 52
Nested for-loop Example (Cont..) #include<iostream> using namespace std; int main ( ) { char ch; for( int row = 0; row < 6; row++) { for (ch=’A’ + row; ch <’A’ + 6; ch++) cout << ch; cout << ’\n’; } return 0; } One of the main applications of nested for loops is in dealing with two- dimensional data like matrices. We will study matrices in the following chapters.
Image of page 53
break statement Forces an immediate break, exiting from while, do while, and for loops. The break statement is useful for breaking out of loops when an unusual condition is detected. continue statement Continue is similar to the break statement and it make the execution jump at the next iteration of while, do while, and for loops. The general form of a continue statement is continue; when continue is encountered in a loop, the next iteration of the loop is immediately begun.
Image of page 54
Break and continue Statements Example count=0; while (count < 30) { cout << "Enter a grade:"; cin >> grade; if (grade < 0 || grade > 100) continue; total += grade; count++; }
Image of page 55
Break/continue Statements Example (Cont..) A better alternative for the above code is the following: if ( grade >=0 && grade<=100) { total +=grade; count++; } The logical operator && and if statement together provides a better approach in C++ to avoid using break and/or continue statement.
Image of page 56
Summary Which loop to choose? While or for loop? A for loop is generally used to create fixed count loops, and a while loop is used to create variable condition loop. In C++, it is a matter of preference, and you will encounter all three styles in your programming career.
Image of page 57

You've reached the end of your free preview.

Want to read all 57 pages?

  • Fall '18
  • Heidar Malki
  • Control flow, Do while loop

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture