Count of n digit numbers whose sum of digits equals to given sum | A Java program using recursive to count numbers with sum of digits as given ' sum ' ; Recursive function to count ' n ' digit numbers with sum of digits as ' sum ' . This function considers leading 0 's also as digits, that is  why not directly called ; Base case ; Initialize answer ; Traverse through every digit and count numbers beginning with it using recursion ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining digits . ; Initialize final answer ; Traverse through every digit from 1 to 9 and count numbers beginning with it ; Driver program to test above function
class sum_dig { static int countRec ( int n , int sum ) { if ( n == 0 ) return sum == 0 ? 1 : 0 ; if ( sum == 0 ) return 1 ; int ans = 0 ; for ( int i = 0 ; i <= 9 ; i ++ ) if ( sum - i >= 0 ) ans += countRec ( n - 1 , sum - i ) ; return ans ; } static int finalCount ( int n , int sum ) { int ans = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) if ( sum - i >= 0 ) ans += countRec ( n - 1 , sum - i ) ; return ans ; } public static void main ( String args [ ] ) { int n = 2 , sum = 5 ; System . out . println ( finalCount ( n , sum ) ) ; } }