Sure.
char k;
for (k = 'a'; k <= 'z'; ++k) { }
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?
La solution
Sure.
char k;
for (k = 'a'; k <= 'z'; ++k) { }
Autres conseils
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 A Uppercase A
66 102 42 01000010 B B Uppercase B
67 103 43 01000011 C C Uppercase C
68 104 44 01000100 D D Uppercase D
69 105 45 01000101 E E Uppercase E
Lowercase is the same, except with different starting value of 97:
97 141 61 01100001 a a Lowercase a
98 142 62 01100010 b b Lowercase b
99 143 63 01100011 c c Lowercase c
100 144 64 01100100 d d Lowercase d
101 145 65 01100101 e e 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 'ç'
.)