# Find the sum of digits of a number at even and odd places in C++

C++Server Side ProgrammingProgramming

Suppose, we have an integer N, We have to find the sum of the odd place digits and the even place digits. So if the number is like 153654, then odd_sum = 9, and even_sum = 15.

To solve this, we can extract all digits from last digit, if the original number has odd number of digits, then the last digit must be odd positioned, else it will be even positioned. After process a digit, we can invert the state from odd to even and vice versa.

## Example

Live Demo

#include<iostream>
using namespace std;
bool isOdd(int x){
if(x % 2 == 0)
return false;
return true;
}
void getSum(int n) {
bool odd_check = isOdd(n);
int odd_sum = 0, even_sum = 0;
while (n != 0) {
if (odd_check)
odd_sum += n % 10;
else
even_sum += n % 10;
odd_check = !odd_check;
n /= 10;
}
cout << "Sum odd : " << odd_sum << endl;
cout << "Sum even : " << even_sum;
}
int main() {
int n = 153654;
getSum(n);
}

## Output

Sum odd : 9
Sum even : 15
Published on 19-Dec-2019 07:48:03