[Help] For - Loop

Can I use char (character) in for loop statement?
How?
Can you give me an example?
char is an integral type, so you can use it as a simple integer:
1
2
3
int arr[10];
for (char i = 0; i < 10; ++i)
    std::cin >> arr[i];

Or you can use it in character context in body of the loop:
1
2
for(char c = '0'; c <= '9'; ++c)
    std::cout << c << '\n';

Please note, that you are likely to have the expected results when iterating for example from a to z, it is not actually set in stone, so computers using some obscure codepage can produce unexpected results.
Yes you can. Just like you will do for an integer.

1
2
3
4
5
6
7
8
for(int i = 97; i <=123; i++)
    cout<<i<<endl;   //prints 97 to 123
   
is the same as 

for(char ch = 'a'; ch <= 'z'; ch++)
    cout<<ch<<endl;    //prints a to z


When using a character in a loop, it is their ASCII codes that are used to do the mathematical operations.



why not use conversions? like static_cast<type>();
Topic archived. No new replies allowed.