# Count Hexadecimal Number in C++

C++Server Side ProgrammingProgramming

We are given a range having start and end and the task is to calculate the count of hexadecimal numbers or alphabets present in the given range.

In computer terms, hexadecimal numbers are those numbers that are having base 16 which means the binary digit can be represented in 16-bit. It consists of integer numbers starting from 0-15. Where 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E and 15 as F.

So, in the below program our task is to find whether the range consists of hexadecimal alphabets or not.

## For Example

Input − start = 10, End = 13
Output − 4

Explanation − There are 4 hexadecimal numbers between 10 and 13 i.e. 10 being A, 11 being B, 12 being C and 13 being D.

Input − start = 15, End = 16
Output − 1

Explanation − There is only one hexadecimal alphabet i.e. 15 as F and 16 is represented as 10 respectively.

## Approach used in the below program is as follows

• Input the range starting from variable let’s say, start and end.

• Declare a variable count to store the count and initialises it with 0

• Start a loop for with i to start and till i is less than or equals to end

• Inside the loop, check if i is greater than or equals to 10 and i is also greater than or equals to 15 then increase the count by 1

• Else, check if i is greater than 15

• Then, set a temporary variable temp with the value of i and traverse while k is not equals to 0

• And check if k%16 is greater than or equals to 10

• Increase the count by 1

• and , set the temp by temp/16

• Return the value of count

• Print the result .

## Example

Live Demo

#include <iostream>
using namespace std;
// Function to count the
int counthexa(int start, int end){
int result = 0;
for (int i = start; i <= end; i++){
// from 10 to 15
if (i >= 10 && i <= 15){
result++;
}
// If i > 15 then perform mod by 16 repeatedly
// till the number is > 0
// If number % 16 > 10 then increase count
else if (i > 15){
int k = i;
while (k != 0){
if (k % 16 >= 10){
result++;
}
k = k / 16;
}
}
}
return result;
}
// Main Function
int main(){
int start = 10, end = 60;
cout << "count is: "<<counthexa(start, end);
return 0;
}

## Output

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

count is: 21
Published on 15-May-2020 09:22:55