Odd and Even program

Write a C++ main function that takes and validates a positive integer number between 99 and 999999 to compute and display the following:
Sum and count of even digits
Sum and count of odd digits
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
#include <iostream> 
#include <iomanip>
#include <string>
#include <math.h>
using namespace std; 
int main ()
{
    int num, d, k, conteven= 0, contodd = 0, sumeven = 0, sumodd = 0; // inputs
    cin >> num; ///entering the number
    while ( (num > 999999) || (num < 99) )
    {
        cout << "ERROR: PLEASE RE-ENTER: "; //validating that it is between 99 and 999999
        cin >> num;
        cout << endl;
    }
    k = log10(num) + 1;   //calculating the number of digits 
    for ( int r = 1; r <= k ; r++)   //using a for loop to separate each digit 
    {
        d = num % 10; /// any number modolus 10 gives the right digit
        num = num/10;   //// any number divide by ten gives the number without the digit on the righy, which I separated and used in d 
        while (d > 0)   /// 0 is neither even nor odd so the digit should be greater than 0
    {
        if ( (d % 2 == 0) ) /// an even number modolus 2 is 0 
        {
        sumeven+=d;   // adding digit to the sum 
        conteven++;   // adding to the count of even digits 
        }
        else
       { 
        contodd++;
        sumodd+=d;    // same as the even part 
       }
    }
    }
    cout << "the even count was " << conteven << " The odd count was " << contodd << endl;
    cout << "The odd sum was " << sumodd << " The even sum was " << sumeven << endl;     //output
    system ("pause");
}

I don't know why the program doesn't work.
Any help, please!
Last edited on
First, please use code tags when posting code. See http://www.cplusplus.com/articles/jEywvCM9/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
k = log10(num) + 1;
for ( int r = 1; r <= k ; r++)
{
  d = num % 10;
  num = num/10;
  while (d != 0)
  {
    if ( (d % 2 == 0) )
    {
      sumeven += d;
      conteven++;
    }
    else
    {
      contodd++;
      sumodd += d;
    }
  }
}

Q: What inside that while-loop does change the value of d?
A: Nothing.

Therefore, if d is not 0, then the loop will continue forever.
Hello Jack Van Stone,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

At the moment what I am seeing is the while loop inside the for loop. At some point "d" will become non zero and the while loop will become an endless loop with no way out.

If I understand this correctly given the number "1234" there are two odd numbers, 1 and 3, with a sum of 4 and a count of 2 and two even numbers with a sum of 6 and a count of 2.

The more I think on it I come to the conclusion that the while loop is not needed just the for loop. When I took out the while it worked fine.

Now when the program starts my console window opens and I am left with a blank screen and a flashing cursor having no idea what to do. A prompt of what to enter would be nice.

A couple of new lines would keep the out from all running together. This may be just my personal choice.

I changed the error message to cout << "ERROR: PLEASE RE-ENTER a number " << (num > 999999 ? " < 999999" : ">99") << ": "; if you would like to use it.

One last point:

It is best not to use "system" anything in a program as this could leave the program vulnerable to attack by hackers who can use this. Also it tends to be specific to Windows and not everyone can use it. If it is your own program and only you will be using it that is OK, but do not let it out to everyone. An alternative you can use is:
1
2
3
4
5
//  This next line may not be needed. If you have to press enter twice put a comment on the line.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
//  Sometimes it is needed.
std::cout << "\n\n Press Enter to continue";
std::cin.get();


Hope that helps,

Andy
I am sorry
Thanks
Can someone please help me by editing the code?
closed account (E0p9LyTq)
What do you expect the results to be, and what are the actual results you are getting?
keskiverto has already explained what the problem is.

To fix it, you need to rework the logic of your while loop. You need to think about what the conditions are for the loop ending, and then ensure those conditions actually occur at some point during the loop.
Points of interest:
- Slightly more descriptive variable names help, e.g. "total_digits" instead of "k".
- 0 is even. Not sure what you were attempting in your internal loop, but just one loops is enough.
- num incrementally fades away to nothing, so you can use this to stop your loop -- while num is non-zero, or, in the C family, while (num) . Thus no need for log10, nor <cmath>.
- declare your variables as close as possible to where you use them.

Side Note: I found that really funny things could happen if your input was too big or too small, as if the range checks become voided.

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
#include <iostream>
#include <limits>

using namespace std;

int main ()
{
    int num = 0;
    int min = 99;
    int max = 999999;
    cout << "Please enter an integer from " << min << " to " <<
            max << ":" << endl;
    cout << "? ";
    while ( cin >> num && (num<min || num>max) )
    {
        cout << "? ";
    }
    if (num==std::numeric_limits<int>::max() ||  
        num==std::numeric_limits<int>::min())
    {
        cout << "Your clever overflow attempt was foiled." << endl;
        return -1;
    }
    
    int odds_sum=0, odds_count=0, evens_sum=0, evens_count=0;
    int d;
    while (num)
    {
        d = num % 10;
        if (d&1)
        {
            odds_sum += d;
            odds_count++;
        }
        else
        {
            evens_sum += d; 
            evens_count++;
        }
        num /= 10;
    }
    cout << "The " << evens_count << " even digit(s) sum to " <<
            evens_sum << ", and the" << endl <<
            "    " << odds_count << " odd digit(s) sum to " <<
            odds_sum << "." << endl;
    
    return 0;
}


Running at https://repl.it/repls/MagnificentRuddySales
Topic archived. No new replies allowed.