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
- Let N be the input number.
- Initialize sum = 0.
- Repeat the following steps while N > 0
- Set r = N % 10. Store the rightmost digit of N in r.
- Set N = N / 10. Remove the rightmost digit of N.
- If r is even, set sum = sum + r. If r is odd, do nothing.
- 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
Read
- C Program to find the sum of odd digits of a given number
- Remove duplicates from an unsorted array in C++
- C Program to print all prime digits of a given number
Sherlock number is a number in which the sum of its digits is an even number. You are given an integer input N. Your task is to return the count of all the Sherlock numbers between 0 to N(0<Sherlock number <=N)