#include <iostream>
using namespace std;
int main()
{
int oddNum, num, oddCount = 0;
cout << "enter an integer: " << endl;
cin >> num;
while (oddNum != 0 && num > 10)
{
num = num % 10;
oddNum = num % 2;
oddCount++;
}
cout << "number of odds is " << oddCount << endl;
}
1) You are using
oddNum variable without first initialize it.
2) Normally,
c = a % b ,
c must smaller than
b . So,
num = num % 10 , num will be alway smaller than 10, which make your loop condition false. I think you should change it to
num = num / 10 3) oddNum = num % 2; , whenever num is an even number, the loop condition will be become false. Your goal is to run through every digit of the number and count the odd number. However, whenever you encounter the even number, your loop will stop.
4) oddCount++;[ , Without checking whether that digit is an odd number or even number, you keep counting every digit.
My solution would be:
while(num>0) {
// Whenever the numb is an odd number, it will return 1.
// In C++, all the non-zero numbers mean true and
// zero means false. I put this condition to check the
// current digit whether it is an odd number or even number
if (num%2) oddCount++;
// Move to the next digit.
num = num / 10;
}
You also able to do it without using condition inside the loop too:
while(num>0) {
oddCount += num % 2;
num = num / 10;
}