简体   繁体   中英

'Try This' exercise on Programming Principles and Practice Using C++, For iteration

I'm studying in this book (self study) and I'd really appreciate if you could help me with a little 'try this' exercise.

This is the code I wrote:

#include "../../../std_lib_facilities.h"

int main()
{
    for (char i ='a'; i <='z'; ++i) {
        int x = i;
        cout << i << '\t' << x << '\n';
    }
    keep_window_open();
    return 0;
}

The next step, according to the book, is: "[...] then modify your program to also write out a table of the integer values for uppercase letters and digits" Is there a function to do that, or do I simply have to repeat the loop starting from A? Thanks

Yes, repeat the loop from 'A' to 'Z' and '0' to '9'.

Assuming your book has covered functions (which it may not have), you might refactor your for loop into its own function perhaps called displayCharactersInTable which takes as arguments the first character and last character. Those would replace the use of 'a' and 'z' in the loop. Thus your main function would look like:

...
displayCharactersInTable('a', 'z');
displayCharactersInTable('A', 'Z');
displayCharactersInTable('0', '9');
...
const char lc_alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const char uc_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int main() {
    for (const char *cur = lc_alphabet; cur < lc_alphabet + sizeof(lc_alphabet); ++cur)
        std::cout << *cur << \t << (int)*cur << '\n';
    for (const char *cur = uc_alphabet; cur < uc_alphabet + sizeof(uc_alphabet); ++cur)
        std::cout << *cur << \t << (int)*cur << '\n';
return 0;
}

This code does not assume that character representations are contiguous (or even increasing alphabetically), so it will work for all character encodings.

int b = 97; // the corresponding decimal ascii code for 'a'
int a = 65; // the corresponding decimal ascii code for 'A'

for(int i = 0; i < 26; ++i)
    cout << char('A' + i) << '\t' << a << '\t' << char('a' + i) << '\t' << b << '\n'; //print out 'A' and add i, print out a, print out 'a' and add i, print out b
    ++a; //increment a by 1
    ++b; //increment b by 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM