Running through entire range of `unsigned char` in `for` loop
c++, for-loop
Solution
Try,
unsigned char i = 0 ;
do {
cout << i << endl ;
}
while ( ++i ) ;
The benefit of `do .. while` over the other forms is you get one free run before the condition is tested. This is an important tool for that reason (if only infrequently used), in a programmer's toolbox.
Problem
I would like to run through the entire range of `unsigned char` in a `for` loop. Say I want to print all numbers from 0 to 255, how should I go about accomplishing that? The following code would be an infinite loop: ``` for (unsigned char i=0; i<=255; i++) cout << i << endl; ``` This one misses out on 0 or 255, depending on whether it is `i++` or `++i` ``` for (unsigned char i=0; ++i<=255; i++) cout << i << endl; ``` I could place a cout before/after the `for` loop to compensate for the missing entry, but I seek a more elegant solution. Any help would be greatly appreciated! (`while` and `do-while` loops are also welcomed!)