C++ program to print sum of all odd digits present in a larger number

Sum of odd digits of a Number in C++

 

C++ program to print sum of all odd digits of a larger number is being explained in this article. Sum of all odd digits can be found by separating each digit using modulo operator from the number and checking whether the digit is odd or not, if odd then add that digit to the variable say sum which track the sum of all odd digits in a given long number.

Example :

  • Sample Input : 921870
  • Sample Output : 17
  • Explanation : Here, in the given input number, odd digits are 9, 1, 7 so there sum will be (1 + 7 + 9)= 17.
C++ Program to find the sum of odd digits in a number

Approach

  • Take a long integer number as input from the user.
  • Store the given input number in a variable say num.
  • Define one variable named sum and initialize it with zero. 
  • That variable will hold the sum of the odd digits.
  • Extract each digit from a number.
  • Check if digit is odd or not.
  • If digit is odd, then add the digit to variable sum.
  • Print the sum.

C++ code

#include<bits/stdc++.h>
using namespace std;

int main(){

long int num;

cout<<"Enter the number :";
cin>>num;

long int sum=0;

while(num>0){

int rem = num%10;

if(rem%2!=0)
sum += rem;

num /= 10;
}

cout<<"\nOdd digits sum is :"<<sum;
return 0;
}
Output:

Enter the number : 2341

Odd digits sum is : 4