Find the sum of digits of a number at even and odd places | C ++ implementation of the approach ; Function to find the sum of the odd and even positioned digits in a number ; If n is odd then the last digit will be odd positioned ; To store the respective sums ; While there are digits left process ; If current digit is odd positioned ; Even positioned digit ; Invert state ; Remove last digit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getSum ( int n ) { bool isOdd = ( n % 2 == 1 ) ? true : false ; int sumOdd = 0 , sumEven = 0 ; while ( n != 0 ) { if ( isOdd ) sumOdd += n % 10 ; else sumEven += n % 10 ; isOdd = ! isOdd ; n /= 10 ; } cout << " Sum ▁ odd ▁ = ▁ " << sumOdd << " STRNEWLINE " ; cout << " Sum ▁ even ▁ = ▁ " << sumEven ; } int main ( ) { int n = 457892 ; getSum ( n ) ; return 0 ; }