Loop efficiency - C++

Following on from jk you could even use the letter itself in the loop (letter <= 'z'). I'd also use a for loop but that's just me.

for( char letter = 'a'; letter <= 'z'; ++letter )
    std::cout << letter << "\t" << static_cast<int>( letter ) << std::endl;

You should aim for clarity first and you try to micro-optimize instead. You could better rewrite that as a for loop:

const int offsetToA = 65;
const int numberOfCharacters = 26;
for( int i = 0; i < numberOfCharacters; ++i ) {
    const int characterValue = i + offsetToA;
    cout << static_cast<char>( characterValue  ) << characterValue << endl;
}

and you can convert between different types - that's called casting (the static_cast construct in the code above).


there is nothing particularly inefficient about the way you are doing it but it certainly is possible to just convert between chars and ints (a char is an integer type). this would mean you only need to store 1 counter rather than the 3 (i, letter + number) you curently have

also, for looping from a fixed start to end a 'for' loop is perhaps more idiomatic (though its possible you havent met this yet!)