Finding the first even digit in an intger

here i wrote the code to print the even digits of an integer in the proper order but i need to just print the first even digit. Im at a lost here and relatively new to c++. any help would be appreciated.


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
 #include <iostream>
using namespace std;

int firstEven (int a) {
        int digit;
        int reverseNum=0;
        while (a > 0)
        {
                reverseNum += (a%10);
                reverseNum *= 10;
                a /= 10;
        }

        reverseNum /= 10;

        while (reverseNum != 0)
        {
                digit=reverseNum%10;
                reverseNum /= 10;
                if (digit%2==0) cout << digit << endl;
        }
        cout << endl; }

int main () {
        int a;
        cout << "Enter an integer to find the first even number in that integer " << endl;
        cin >> a;
        firstEven(a);
        return 0;
}
Your can make a little change to your second while loop. For example:

1
2
3
4
5
6
7
8
9
10
11
bool done = false;  // did we print a number before?
while (reverseNum != 0 && !done)
{
    digit = reverseNum % 10;
    reverseNum /= 10;
    if (digit % 2 == 0)
    {
        cout << digit << endl;
        done = true;  // indicates that we have printed a number
    }
}
Topic archived. No new replies allowed.