I'm working on a programming lab where I need to count how many digits are in an integer between 0 and 9999. The integer should be of type int, and I can only use if statements, not loops. My approach was to divide the number by 10 repeatedly and count how many times I do this, but I keep running into a problem. For a two-digit number, my program incorrectly counts it as four digits, which is obviously not right. Here's the code I have so far:
#include
using namespace std;
int main() {
int inputNum;
int numDigits;
cin >> inputNum;
int count = 0;
numDigits = inputNum / 10;
if (numDigits == 0)
count = 1;
else if (numDigits > 0)
{
numDigits = inputNum / 10;
count = 2;
if (numDigits > 0)
{
numDigits = inputNum / 10;
count = 3;
if (numDigits > 0)
{
numDigits = inputNum / 10;
count = 4;
}
}
}
if (count == 1)
cout << count << " digit" << endl;
else
cout << count << " digits" << endl;
return 0;
}
4 Answers
It looks like the issue is that you're constantly resetting `numDigits` to `inputNum / 10` instead of dividing `numDigits` by 10 each time you go through your conditions. You need to change your assignments after the first `else if` to `numDigits = numDigits / 10;` so that it reflects the updated number after each division. That should fix your counting problem.
Just a tip: make sure to check the value of `numDigits` at different points in your code. Adding some debug prints (like `cout << "Debug: " << numDigits << endl;`) can help you see how its value changes, which is crucial for understanding why your counting logic isn't working as expected.
You're on the right track with your approach, but remember that your initial assignments to `numDigits` aren't being updated properly. After checking for 1 digit, when you check for 2 digits, you should be working with the result of that first division, not starting from `inputNum` again. So replace `numDigits = inputNum / 10;` with `numDigits = numDigits / 10;` after your first conditional check.
I noticed you're not using any loops in your program. Since you're repeating the same operation for each digit, a loop would actually help you avoid this repetition. But given the lab's restriction on using branches only, that's going to complicate things. If they allowed loops, counting digits would be a lot simpler!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically