Home »
C++ Programs
C++ program to find the largest character in the string using class
Submitted by Shubh Pachori, on September 05, 2022
Problem statement
Given a string, we have to find the largest character in the string using the class and object approach.
Example:
Input: Enter String : string
Output: Largest Alphabet is t
C++ code to find the largest character in the string using the class and object approach
#include <iostream>
using namespace std;
// create a class
class String {
// private data member
private:
char str[30];
// public functions
public:
// putString() function to
// insert the string
void putString() {
cout << "Enter String : ";
cin.getline(str, 30);
}
// largest() function to find the largest
// character in the string
char largest() {
// let the first element of the string
// is the largest
char max = str[0];
// for loop to read the whole string from the
// second character to the last character
for (int index = 1; str[index]; index++) {
// if the character at the index is greater than
// the max then the character will replace the
// character at the max
if (str[index] > max) {
max = str[index];
}
}
// returning the largest character
return max;
}
};
int main() {
// create an object
String S;
// char type variable to store the
// largest character in it
char max;
// function is called by the object
// to store the string
S.putString();
// largest() function is called
// by the object to find the
// largest character in the string
max = S.largest();
cout << "Largest Alphabet is " << max;
return 0;
}
Output
RUN 1:
Enter String : shubh
Largest Alphabet is u
RUN 2:
Enter String : Hello, world!
Largest Alphabet is w
Explanation
In the above code, we have created a class String, one char type string data member str[30] to store the string, and public member functions putString() and largest() to store the given string and to find the largest character in it.
In the main() function, we are creating an object S of class String, reading character values by the user of the string using the putString() function, and finally calling the largest() member function to find the largest character in the given string. The largest() function contains the logic to find the largest character in the given string and printing the result.
C++ Class and Object Programs (Set 2) »