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 ; To store the respective sums ; Converting integer to string ; Traversing the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getSum ( int n ) { int sumOdd = 0 , sumEven = 0 ; string num = to_string ( n ) ; for ( int i = 0 ; i < num . size ( ) ; i ++ ) { if ( i % 2 == 0 ) sumOdd = sumOdd + ( int ( num [ i ] ) - 48 ) ; else sumEven = sumEven + ( int ( num [ i ] ) - 48 ) ; } cout << " Sum ▁ odd ▁ = ▁ " << sumOdd << " STRNEWLINE " ; cout << " Sum ▁ even ▁ = ▁ " << sumEven << " STRNEWLINE " ; } int main ( ) { int n = 457892 ; getSum ( n ) ; return 0 ; }