Count array elements having sum of digits equal to K | Java program for the above approach ; Function to calculate the sum of digits of the number N ; Stores the sum of digits ; Return the sum ; Function to count array elements ; Store the count of array elements having sum of digits K ; Traverse the array ; If sum of digits is equal to K ; Increment the count ; Print the count ; Driver code ; Given array ; Given value of K ; Size of the array ; Function call to count array elements having sum of digits equal to K
public class GFG { static int sumOfDigits ( int N ) { int sum = 0 ; while ( N != 0 ) { sum += N % 10 ; N /= 10 ; } return sum ; } static void elementsHavingDigitSumK ( int [ ] arr , int N , int K ) { int count = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( sumOfDigits ( arr [ i ] ) == K ) { count ++ ; } } System . out . println ( count ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 23 , 54 , 87 , 29 , 92 , 62 } ; int K = 11 ; int N = arr . length ; elementsHavingDigitSumK ( arr , N , K ) ; } }