URGENT!
Hello, I am having trouble trying to figure out how I need to do this problem for my C++ class.
The assignment is asking me to write a program that will count the number of EVEN digits in a given number.
This is my first Programming class so please bare with me.
My current code is below:
int countEven (int n);
int even_count = 0;
int n;
while (n > 0)
{
int rem = n % 10;
if (rem % 2 == 0)
even_count++;
}
if (even_count % 2 == 0)
even_count++;
std::cout << "Even Digits Program\n";
std::cout << "Enter a number greater than 0.\n";
std::cin >> n;
std::cout << "This number has " << even_count << " even digit(s).";
The problem I am having is that it keeps returning 1 even digit for any number I input.
If you could help me with this I would greatly appreciate it.
Please use code tags, code looks like a broken down apartment at night otherwise:
[code]
//Code Goes Here
[/code]
If I got this right, you need to count the amount of even numbers a number contains? For example, 5 would contain 2 and 4 as even numbers?
If so, you can simply make a loop that starts with the number, checks if it's divisible by 2, and then subtract 1 from it, and then do it all over again:
1 2 3 4 5 6 7 8
std::cout << "Enter a number greater than 0.\n";
std::cin >> n;
for(int i = n; i >0; i--)
{
if(i % 2 == 0)
even_count++;
}
However, using a loop is overkill. Figuring out this number is as simple as doing integer division. Divide the number taken in by 2, and whatever the answer is how many even numbers:
#include <iostream>
// program that will count the number of EVEN digits in a given number.
int main()
{
// read in a positive integer
// (do something with the number n only after it has been read in)
int n ;
std::cout << "Enter an integer greater than 0: " ;
std::cin >> n ;
if( n > 0 ) // if n is a positive integer
{
int cnt_even_digits = 0 ;
while( n != 0 ) // while at least one digit is left
{
// if the last digit is even, increment the count of even digits
constint last_digit = n%10 ;
if( last_digit%2 == 0 ) ++cnt_even_digits ;
// knock off the last digit from n and repeat
n /= 10 ;
}
std::cout << "the number entered has " << cnt_even_digits << " even digits\n" ;
}
else std::cout << "invalid input\n" ;
}
#include <iostream>
usingnamespace std;
int numEven( int N ) { return N > 0 ? 1 - N % 2 + numEven( N / 10 ) : 0; }
int main()
{
int n ;
cout << "Enter a positive integer: "; cin >> n;
cout << "This has " << numEven( n ) << " even digits.\n";
}