Count even and odd digits in an Integer in C++

C++Server Side ProgrammingProgramming

We are given with an integer number and the task is to count the even numbers and the odd numbers in a digit. Also, we will keep check on whether the even digits in an integer are occurring an even number of times and also the odd digits in an integer are occurring an odd number of times.

For Example

Input − digit = 12345
Output − count for even digits = 2
      count for odd digits = 3

Explanation − Yes, Also, even digits are occurring even number of times i.e. 2 and odd digits are occurring odd number of times i.e. 3

Input − digit = 44556
Output − count for even digits = 3
      count for odd digits = 2

Explanation-: NO, as even digits are occurring odd number of times i.e. 3 and odd digits are occurring even number of times i.e. 2

Approach used in the below program is as follows

  • Input an integer values consisting of odd and even digits

  • Declare two variables, one for counting odd digits and another for counting even digits and initialise them with 0.

  • Start the loop, while the digit is greater than 0 and decrement it with “digit/10” such that we will be fetching individual digits in an integer.

  • If the digit is divisible by than it will be even else it will be odd.

  • If digit found is even, increment the count for even by 1 and if the digit found is odd, increment the count for odd by 1

  • Now, for checking whether the even digits are occurring an even number of times, divide the even count by 2, if it comes 0 then it is occurring an even number of times else it's occurring an odd number of times.

  • And for checking whether the odd digits are occurring an odd number of times, divide the odd count by 2, if it comes !0 then it is occurring an odd number of times else it's occurring an even number of times.

  • Print the result.

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   int n = 12345, e_count = 0, o_count = 0;
   int flag;
   while (n > 0){
      int rem = n % 10;
      if (rem % 2 == 0){
         e_count++;
      } else {
         o_count++;
      }
      n = n / 10;
   }
   cout << "Count of Even numbers : "<< e_count;
   cout << "\nCount of Odd numbers : "<< o_count;
   // To check the count of even numbers is even and the
   // count of odd numbers is odd
   if (e_count % 2 == 0 && o_count % 2 != 0){
      flag = 1;
   } else {
      flag = 0;
   }
   if (flag == 1){
      cout << "\nYes " << endl;
   } else {
      cout << "\nNo " << endl;
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of Even numbers : 2
Count of Odd numbers : 3
Yes
raja
Published on 15-May-2020 12:14:18
Advertisements