# C/C++ Program to Find the Sum of Even Digits in a Number

Write a program to find the sum of even digits in a given integer number in C/C++.

Example,

```Input
5234123
Output
8

Explaination
There are 4 even digits in the input number - { 2, 4, 2 }
2 + 4 + 2 = 8```

We will discuss 2 techniques to solve this question.

## Method 1

In this method, we read each digit of the input number using % operator.

Steps

1. Let N be the input number.
2. Initialize sum = 0.
3. Repeat the following steps while N > 0
1. Set r = N % 10. Store the rightmost digit of N in r.
2. Set N = N / 10. Remove the rightmost digit of N.
3. If r is even, set sum = sum + r. If r is odd, do nothing.
4. The sum of even digits of N is stored in sum.
``````#include<stdio.h>

int sum_of_even_digits(int n) {

int r, sum = 0;

// reading each digit of n
while (n > 0) {

r = n % 10;	// storing rightmost digit of n in r
n = n / 10;	// removing rightmost digit of n

// if r is even, add r to sum
if (r % 2 == 0){
sum = sum + r;
}

}

return sum;

}

int main() {

int n;
printf("Enter a Number: ");
scanf("%d", &n);

printf("Sum of Even Digits: %d", sum_of_even_digits(n));

}``````

Output

``````Enter a Number: 123456
Sum of Even Digits: 12``````

## Method 2

In this method, we first convert the given number to a string using itoa() and then traverse the string using a loop and sum the even digits.

``````#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int sum_of_even_digits(int n) {

int i, sum = 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, add str[i] to sum
// we are substracting '0' from str[i]
// to convert character to integer digit
if ((str[i] - '0') % 2 == 0) {
sum = sum + (str[i] - '0');
}

}

return sum;

}

int main() {

int n;
printf("Enter a Number: ");
scanf("%d", &n);

printf("Sum of Even Digits: %d", sum_of_even_digits(n));

}``````

Output

``````Enter a Number: 1232433
Sum of Even Digits: 8``````