Procedural: Flow control structuresTrail Index | Procedural | Flow Control Structures Flow control structures allow your program to deviate from the linear, one after the other sequence of instruction execution.
/** * Flow control structures */ #include <iostream> int main() { using namespace std; // an indexed loop int a=0; for (int i=0;i<30;i++) { a=a+.1; // would be nice to get a warning here... cout<<i<<" step: "<<a<<endl; } // an if if (a<1) { cout<<"something wrong above..."; } // an if-else structure double b; if (a>3) { b=a/3; } else { b=a/2; } { // a non-indexed while loop double sum=0; int count=0; while (sum<10) { sum+=.3; count++; } cout<<"Sum="<<sum<<", count="<<count<<endl; } { // a non-indexed while loop, with an "emergency exit" double sum=0; int count=0; while (sum<10) { ++count; if (count>10) break; // exit the loop NOW! sum+=.3; } cout<<"Sum="<<sum<<", count="<<count<<endl; // a break can be anywhere, inside any kind of loop } // like while() {}, but evaluate at end // useful for looping at least once do { ;//nothing } while (false); { /* * switch is like a whole bunch of if..else if.. else * it's more readable and much more efficient * (it does not need to evaluate a condition each time) * but only works on an integer expression */ int idx=3; switch (idx) { case 1: cout<<"one!\n";break; case 2: cout<<"two!\n";break; default: cout<<"not one and not two\n"; } // note the use of break } return 0; // zero means all is well } The peculiar syntax of "for" in C++ deserves to be discussed, considered that it's one of the most commonly used control structures. In BASIC, for example, the simplest indexed loop is FOR i=0 TO 10 ... NEXT i and in Fortran do i=1,10 ... enddo in C/C++, this is int i; for(i=0;i<=10;i++) { ... } which makes explicit the initial assignment int i=0; while (i<=10) { ... i++; } Please note also that in C++ you can use the more compact form below, where the index variable for(int i=0;i<=10;i++) { ... } In rare cases, for example where you have an int i; for(i=0;i<=10;i++) { if ( a[i]==3 ) break; } if (i<10) cout<<" value 3 found in the array at index "<<i<<endl; (we will see the array data structures later) < Variables | Trail Index | Functions > |