Hello. I've been asked to do this function which basically reads an inputted integer and then returns the number of even, odd, and zero digits in this integer. Here's my attempt on solving it.
#include<iostream>
usingnamespace std;
int integer;
void SumEvenZero(int &integer, int &evenCount, int &oddCount, int &zeroCount)
{
int counter;
int digits = 0;
cin>>integer;
while(integer != 0)
{
integer = integer/10;
digits++;
}
for (counter = 0; counter < digits; counter++)
{
if(counter % 2 == 0 || counter == 0)
{
evenCount++;
}
elseif (counter % 2 == 1)
{
oddCount++;
}
elseif (counter == 0)
{
zeroCount++;
}
}
cout<<endl;
}
int main()
{
int counter;
int evenCount = 0;
int oddCount = 0;
int zeroCount = 0;
int digits;
cout<<"Enter an integer: ";
SumEvenZero(integer, evenCount, oddCount, zeroCount);
cout<<"The number of even digits: "<<evenCount<<endl;
cout<<"The number of odd digits: "<<oddCount<<endl;
cout<<"The number of zeros: "<<zeroCount<<endl;
return 0;
}
So, here it reads 0,1,2,3 which therefore outputs: 2 even digits 2 odd digits and 0 zeros (it is reading the counter). How can I read it as (say I inputted 1008) 1, 0 , 0 , 8 and output: 3 even, 1 odd, 2 zeros?
The for loop is not necessary. All of your work can be done in the while loop.
Algorithm:
Get the last digit of the integer using the % operator.
Check if the digit is odd, even or zero using if-statements, and increment the appropriate count variable.
Remove the last digit from the integer using the / operator.
Repeat until integer is 0.