Home »
C++ Programs
C++ program to find the smallest character in the string using class
Submitted by Shubh Pachori, on September 06, 2022
Problem statement
Given a string, we have to find the smallest character in the string using the class and object approach.
Example:
Input:
Enter String : string
Output:
Smallest Alphabet is g
C++ code to find the smallest 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);
}
// smallest() function to find the smallest
// character in the string
char smallest() {
// let the first element of the string
// is the smallest
char min = 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
// smaller than the min then the character
// will replace the character at the min
if (str[index] < min) {
min = str[index];
}
}
// returning the smallest character
return min;
}
};
int main() {
// create an object
String S;
// char type variable to store
// the smallest character in it
char min;
// function is called by the object
// to store the string
S.putString();
// smallest() function is called by
// the object to find the
// smallest character in the string
min = S.smallest();
cout << "Smallest Alphabet is " << min;
return 0;
}
Output
RUN 1:
Enter String : Hello
Smallest Alphabet is H
RUN 2:
Enter String : includehelp
Smallest Alphabet is c
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 smallest() to store the given string and to find the smallest 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 smallest() member function to find the smallest character in the given string. The smallest() function contains the logic to find the smallest character in the given string and printing the result.
C++ Class and Object Programs (Set 2) »