Count numbers with unit digit k in given range in C++

We are given an interval [first,last]. The goal is to find the count of numbers that have a unit digit k and lie between range [first,last].

We will do this by traversing from i=first to i=last. For each number i compare its unit digit with the k, if they are the same increment the count.

Let’s understand with examples.

Input − first=8 last=40 , k=8

Output − Count of numbers with unit digit k − 4


Numbers between 8 and 40 with unit digit = 8
8,18, 28, 38

Input − first=100 last=200 , k=9

Output − Count of numbers with unit digit k − 10


Numbers between 100 and 200 with unit digit = 9
109, 119, 129, 139, 149, 159, 169, 179, 189, 199.

Approach used in the below program is as follows

  • We take two integers first and last to define range [first, last].

  • Function getCount(int fst, int lst, int k) takes range variables and k and returns the count of numbers between fst and lst and have unit digit as k.

  • Take the initial count as 0.

  • Using for loop start from i=fst to i=lst, for each i calculate unit digit as ldigit=i%10.

  • If ldigit==k, increment count.

  • Return count as result.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getCount(int fst,int lst,int k){
   int count=0;
   for(int i=fst;i<=lst;i++){
      int ldigit=i%10; //to get last digit
      if(ldigit==k) //if both are equal increment count
         { ++count; }
   return count;
int main(){
   int first = 5, last = 30;
   int K=5;
   cout<<"Numbers with unit digit K in range:"<<getCount(first, last, K);
   return 0;


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

Numbers with unit digit K in range:3