1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <iostream> // <-- needed for cin, cout, endl
#include <math.h> // <-- needed for pow() and log10()
using namespace std;
/*This program seperates the integer into a series of digits.
The digits will be reversed, but that isn't a problem.*/
void seperateDigits(int integer, int digitCount, int digit[]){
for (int i = 0; i < digitCount; i++){
digit[i] = int(integer / pow(10., double(i)));
/*integer / 10^i cuts off end digit (e.g. 123 first time,
12 second time, 1 third time)*/
digit[i] = int(digit[i]) % 10;
/*Gets the final digit (e.g. 123 becomes 3,
12 becomes 2, 1 becomes 1)*/
}
}
/*This program will count the even, odd, and zero digits.
The correct count will be assigned to ctreven, ctrodd, and
ctrzero without having a return value. This can be done by
using a "pass by refernce" method.*/
void countDigits(int &ctreven, int &ctrodd, int &ctrzero, int digitCount, int digit[])
{
for(int i = 0; i < digitCount; i++)
{
if(digit[i] == 0){
ctrzero++;
}
else if(digit[i]%2 == 0){
ctreven++;
}
else{
ctrodd++;
}
}
}
int main()
{
int integer;
// These next three need to start at 0
int ctreven = 0;
int ctrodd = 0;
int ctrzero = 0;
cout<<"Enter an integer: ";
cin >> integer; // This is needed to accept user's input
cout << endl; // <-- just for formatting
int digitCount = int(log10(integer)) + 1; // log10(integer) + 1 gives you the number of digits
int digit[digitCount]; // This array will hold the digits
seperateDigits(integer, digitCount, digit); // This runs the function to seperate
countDigits(ctreven, ctrodd, ctrzero, digitCount, digit); // This runs the function to count
/*Now that the digits have been counted, the 3 variables
(ctreven, ctrodd, ctrzero) have the correct values*/
cout << "The number of even digits: " << ctreven << endl;
cout << "The number of odd digits: " << ctrodd << endl;
cout << "The number of zeros: " << ctrzero << endl;
cout << endl << endl; // <-- just for formatting
return 0;
}
|