C/C++ Program to Find the Sum of Odd Digits in a Given Number

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

Example,

Input
1234253
Output
12

Explaination
There are 4 odd digits in the input number - { 1, 3, 5, 3}
1 + 3 + 5 + 3 = 12

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. We are storing the rightmost digit of N in r.
    2. Set N = N / 10. We are removing the rightmost digit of N.
    3. If r is odd, set sum = sum + r. If r is even, do nothing.
  4. The sum of odd digits is stored in sum.
#include<stdio.h>

int sum_of_odd_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 odd, add r to sum
		if (r % 2 == 1)
			sum = sum + r;

	}

	return sum;

}

int main() {

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

	printf("Sum of Odd Digits: %d", sum_of_odd_digits(n));

}

Output

Enter a Number: 1234253
Sum of Odd 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 odd digits.

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

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

	}

	return sum;

}

int main() {

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

	printf("Sum of Odd Digits: %d", sum_of_odd_digits(n));

}

Output

Enter a Number: 413332
Sum of Odd Digits: 10

Read

Leave a Comment

Your email address will not be published. Required fields are marked *