Program to find the largest and smallest ASCII valued characters in a string in C++


In this problem, we are given a string. Our task is to create a program to find the largest and smallest ASCII valued characters in a string in C++.

Code Description − Here, we have a string that consists of both upperCase and lowerCase characters. And we need to find the characters that have the largest and the smallest ASCII value character.

Let’s take an example to understand the problem,

Input

str = “TutroialsPoint”

Output

Largest = u smallest = P.

Explanation

According to ASCII values, upperCase characters are smaller than lowerCase characters.

So, the smallest character of upperCase characters (A) has overall the smallest ASCII value. The largest character of lowerCase characters (z) has the overall largest ASCII value.

Solution Approach

A simple approach would be directly iterating over the string and finding the max and min characters based on their ASCII values.

Here, ASCII value comparison can be done using comparison with ‘A’ and ‘z’ characters.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
void findMaxMinAlphabet(char str[], int n){
   char maxChar = str[0];
   char minChar = str[0];
   for(int i = 0; i < n - 1; i++){
      if (str[i] > maxChar)
         maxChar = str[i];
      if(minChar > str[i])
         minChar = str[i];
   }
   cout<<"Maximum Alphabet: "<<maxChar<<"\nMinimum Alphabet: "<<minChar;
}
int main() {
   char a[]= "TutorialsPoint";
   int size = sizeof(a) / sizeof(a[0]);
   findMaxMinAlphabet(a, size);
   return 0;
}

Output

Maximum Alphabet: u
Minimum Alphabet: P

Updated on: 15-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements