Write a program to count the number of even digits in a given number in C/C++.
For example,
Input 1225678 Output 4
Approach
To solve this problem, we will read each digit of the input number one-by-one using the Modulus and Division operator and check if the digit is even or not.
Steps
- Take input from the user. Let the input be N.
- Initialize a variable count = 0, this variable stores the even digit count.
- Repeat the following steps while N is greater than zero.
- Set temp = N % 10. This step stores the right-most digit of N in temp.
- Check if temp is even or not. If temp is even, increment count, otherwise do nothing.
- Set N = N / 10. This step removes the right-most digit of N.
- The number of even digits in the input integer is equal to count.
#include<stdio.h>
int count_even_digits(int n) {
int temp, count = 0;
// reading each digit of n
while (n > 0) {
temp = n % 10; // storing rightmost digit of n in temp
n = n / 10; // removing rightmost digit of n
// if temp is even, increment count
if (temp % 2 == 0) {
count++;
}
}
return count;
}
int main() {
int n;
printf("Enter a Number: ");
scanf("%d", &n);
printf("Number of Even Digits: %d", count_even_digits(n));
}
Output
Enter a Number: 22358
Number of Even Digits: 3
Method 2
In this method, we first convert the input number to a string using itoa() and then iterate the string and check if a digit is even or not.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int count_even_digits(int n) {
int i, count = 0;
char str[100];
// converting n to string and storing the string in str[]
itoa(n, str, 10);
// reading each character of str[]
for (i = 0; i < strlen(str); ++i) {
// if str[i] is even, increment count
// we are substracting '0' from str[i]
// to convert character to corresponding integer digit
if ((str[i] - '0') % 2 == 0) {
count++;
}
}
return count;
}
int main() {
int n;
printf("Enter a Number: ");
scanf("%d", &n);
printf("Number of Even Digits: %d", count_even_digits(n));
}
Output
Enter a Number: 23334
Number of Even Digits: 2
Read