Count of numbers from range[L, R] whose sum of digits is Y in C++

C++Server Side ProgrammingProgramming

We are provided two numbers START and END to define a range of numbers.The goal is to find all the numbers in the range [START,END] which have sum of digits equal to a given number Y.

We will do this by traversing numbers from START to END and for each number we will count the sum of its digit using a while loop. If this sum is equal to Y, increment count.

Let’s understand with examples.


START=10 END=20 Y=4


Numbers such that digit sum is equal to Y: 1


Number 13 has digit sum equal to 4.


START=10 END=50 Y=5


Numbers such that digit sum is equal to Y: 5


Numbers 14, 23, 32, 41 and 50 have digit sum 5.

Approach used in the below program is as follows

  • We take integers START, END, Y.

  • Function digitSum(int start, int end, int y) returns the count of numbers with digitsum=y

  • Take the initial variable count as 0 for such numbers.

  • Take variable digsum as 0

  • Traverse range of numbers using for loop. i=start to i=end

  • Now for each number num=i, using while loop check if number is >0.

  • calculate digsum+=num%10. Reduce num=num/10 to add the next digit.

  • At the end of the while, check if ( digsum == d ). If true increment count.

  • At the end of all loops count will have a total number which satisfies the condition.

  • Return the count as result.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int digitSum(int start, int end, int y){
   int count = 0;
   int digsum = 0;
   for (int i = start; i <= end; i++){
      int num=i;
         digsum+=num%10; //sum of digits
      if(digsum==y) //original number is i{
         //cout<<i<<" ";
   return count;
int main(){
   int START = 100;
   int END = 1000;
   int Y = 5;
   cout <<"Numbers such that digit sum is equal to Y: "<<digitSum(START,END,Y);
   return 0;


If we run the above code it will generate the following output −

Numbers such that digit sum is equal to Y: 15
Published on 31-Oct-2020 04:56:13