I am very new to programming, so I apologize if this question seems absurdly simple. I am working on some extra questions in the current chapter of my C++ book. I have actually found a correct answer to the problem, but while doing so, I ran into a situation that is driving me crazy because I can’t figure out WHY one particular solution works and another one doesn’t.
So, the problem asks to print the ASCII values between 32 and 127 in a few rows with 16 characters per row. The solution I have come to (that works correctly) is this:
#include <iostream>
using namespace std;
int main()
{
char letter;
int count = 0;
for (letter = 32; letter < 127; letter++, count++)
{
if (count == 16)
{
cout << endl;
count = 0;
}
cout << letter << " ";
}
cout << endl;
return 0;
}
Again, the above code runs fine and does what I want it to. The difficulty lies in something I tried before this. I attempted to do the same problem with a nested while loop, like so:
#include <iostream>
using namespace std;
int main()
{
char letter = 32;
int count;
while (letter < 127)
{
count = 0;
while (count < 16)
{
cout << letter << " ";
letter++;
count++;
}
cout << endl;
}
cout << endl;
return 0;
}
This while loop just runs infinitely and also spits out some garbage after the ASCII characters I want, and I can’t figure out why. What’s even weirder is if I change the variable ‘letter’ in the code with while loops to an int instead of a char, it runs exactly the way I want it to and terminates when it should, just displaying the actual numbers instead of the ASCII values.
It’s only when ‘letter’ is a char that I get an infinite loop. I’m sure it’s something really simple, and I might just be too tired to see it right now, but any help/hints would be much appreciated! Even though I technically got the answer, it’s driving me crazy that I don’t know WHY the second answer fails so horribly.
Thanks in advance.
The answer is simple, true enough. Here is what happens – (signed)char can have values in the range [-128, 127] in the inner loop after you output the row up to 112, you increment count with another 16 and therefor you also increment letter with 16, this makes letter equal to 112 + 16 = 128, which due to the range of signed char is actually overflowing and becomes -128. So after this execution of the inner loop the condition of the outer loop still holds: -128 < 127. That is also why you get weird chars – these will be the values between -128 and 32.
How to fix the problem? Change the check in the inner loop:
while (count < 16 && letter < 127)