for

More Control Statements in C++

The for statement allows us to execute a block of code a certain number of times. The for statement has three elements – the initial statement, the condition, and the iteration statement, each of these statements is separated by a semicolon and are together surrounded by parentheses.

#include <iostream>

using namespace std;

int main(void){

    int total, current, counter;

    current = 0;
    total = 0;
    for(counter = 0; counter < 10; counter++){
        cout  <<  "Enter a number: ("  <<  10 - counter  <<  " available entries)"  <<  endl;
        cin  >>  current;
        total += current;    
    }

    cout  <<  "The total is "  <<  total  <<  endl;

    return 0;

}

Generally speaking, it’s a good idea in C and C++ to orient ourselves around zero-based counting, where, for instance, we count to five as 0,1,2,3,4. We ought to do this because for loops work really well when looping through arrays, and arrays are always zero-indexed.

#include <iostream>

using namespace std;

int main(void){

    int celsiusTemps[10];

    int i;

    //initialize array
    for(i = 0; i < 10; i++){
        celsiusTemps[i] = i * 5;
    }

    //read array
    for(i = 0; i < 10; i++){
        cout << "Celsius: " << celsiusTemps[i] << "\t";
        cout << "Farenheit: " << celsiusTemps[i] * 9 / 5 + 32 << endl;
    }

    return 0;

}

The switch statement is similar to a chain of if-else statements. The switch statement begins with the keyword switch followed by an expression in parenthesis and then a colon.  Then, in hierarchical order, there are a set of case blocks, each block begins with the keyword case followed by a constant value and then a colon, and then contains one or more statements that then ends with the break statement. If the break statement is omitted, then execution will “fall through” to the next block; this may or may not be a good thing.

#include <iostream>
#include <string>

using namespace std;

string getEnding(int num);

int main(void){

    for(int i = 0; i <= 30; i++){
        cout << i << getEnding(i) << endl;
    }

    return 0;

}



string getEnding(int num){
    //get last digit
    string s;
    if(num > 10 && num < 14){
        num+=3;
    }
    switch (num % 10){
        case 0:
            s = "th";
            break;
        case 1:
            s = "st";
            break;
        case 2:
            s = "nd";
            break;
        case 3:
            s = "rd";
            break;
        default:
            s = "th";    
    }

    return s;
}

Basically, the switch statement evaluates the value of a given expression and branches to the appropriate case label.

Note that the case labels can be in any order, but that they must be constants.

Buy my book! http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/