Question

when for example you increase a variable with a for you do this

for(k=1; k<21; k++)

right? and this means that the for sequence will be repeated until k is 20 so, is there any way to increase a character variable? like a,b,c,d,e,f...? thanks.

the thing is that i want to make a table but with characters and with a character increasing by one.

I havent tried with anything since im a student an i just dont know how to do something like that, or is there any command that could do this?

Was it helpful?

Solution

Sure.

char k;
for (k = 'a'; k <= 'z'; ++k) { }

OTHER TIPS

All characters have an associated numeric value. Take look at the following link: http://www.ascii-code.com/

Here's a snippet: You'll see that the capitol character 'A' begins at a numeric value of 65, then B, C, D, etc all are an additional 1 more.

65  101 41  01000001    A   &#65;       Uppercase A
66  102 42  01000010    B   &#66;       Uppercase B
67  103 43  01000011    C   &#67;       Uppercase C
68  104 44  01000100    D   &#68;       Uppercase D
69  105 45  01000101    E   &#69;       Uppercase E

Lowercase is the same, except with different starting value of 97:

97  141 61  01100001    a   &#97;       Lowercase a
98  142 62  01100010    b   &#98;       Lowercase b
99  143 63  01100011    c   &#99;       Lowercase c
100 144 64  01100100    d   &#100;      Lowercase d
101 145 65  01100101    e   &#101;      Lowercase e

Since a character is really just representing this ascii integer value, you can do as Lashane indicated in his comment and loop through as you would an integer.

char is a (relatively narrow) integer type, and you can perform arithmetic on char values just as you can on any other numeric type.

But be careful. The language only guarantees that the numeric values of '0', '1', ..., '9' are consecutive, so this:

for (char c = '0'; c <= '9'; c ++) {
    // ...
}

will iterate over the ten decimal digits. The language makes no such guarantee about letters, so this:

for (char c = 'a'; c <= 'z'; c ++) {
    // ...
}

is not guaranteed to iterate over the 26 lowercase letters.

In practice, you're not particularly likely to run into a system where it doesn't work. It happens to work on any system using an ASCII-based character system (that includes Latin-1, Unicode, etc.). But IBM mainframes use a different character set, EBCDIC, in which the letters do not have consecutive values.

If you need to iterate over the uppercase letters, you can either not worry about the fact that your code isn't 100% portable, or you can write code that doesn't depend on their representations:

const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < sizeof alphabet; i ++) {
     const char c = alphabet[i];
     // ...
}

(But even this will skip other lowercase letters like 'é' and 'ç'.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top