# Count and Print the alphabets having ASCII value in the range [l, r] in C++

C++Server Side ProgrammingProgramming

We are given with a string of any length and the task is to calculate the count and print the alphabets in a string having ASCII value in the range [l,r]

## ASCII value for character A-Z are given below

ABCDEFGHIJKLMNOPQRS
65666768697071727374757677787980818283

TUVWXYZ
84858687888990

ASCII value for characters a-z are given below −

abcdefghijklmnopqrs
9
7
9
8
9
9
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
11
0
11
1
11
2
11
3
11
4
11
5

tuvwxyz
116117118119120121122

## For Example

Input − String str = “point
First = 111, Last = 117
Output − characters in the given range are: p, o , t
Count is: 3

Explanation − since p, o and t lies in the range of [111, 117] these characters will be counted.

Input − String str = “ABCZXY
First = 65, Last = 70
Output − characters in the given range are: A, B, C
Count is: 3

Explanation − since A, B and C lies in the range of [65, 70] these characters will be counted.

## Approach used in the below program is as follows

• Input the string, start and end values to create the range and store it in variables let’s say, str.

• Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.

• Take a temporary variable that will store the count of characters

• Start the loop from i to 0 till i is less than the length of the string

• Inside the loop, check if start is less than equals to str[i] and str[i] is less than equals to end

• Now, increase the count by 1 if condition holds true and print str[i]

• Return the count

• Print the result

## Example

Live Demo

#include <iostream>
using namespace std;
// Function to count the number of
// characters whose ascii value is in range [l, r]
int count_char(string str, int left, int right){
// Initializing the count to 0
int count = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
// Increment the count
// if the value is less
if (left <= str[i] and str[i] <= right) {
count++;
cout << str[i] << " ";
}
}
// return the count
return count;
}
int main(){
string str = "tutorialspoint";
int left = 102, right = 111;
cout << "Characters in the given range";
cout << "\nand their count is " << count_char(str, left, right);
return 0;
}

## Output

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

Characters in the given range
and their count is o i l o i n 6
Published on 15-May-2020 10:29:27