In C++ code 1. Most Frequent Character – Write a program that contains a functio
ID: 3764947 • Letter: I
Question
In C++ code
1. Most Frequent Character – Write a program that contains a function that accepts a string object as its argument. The function should return the character that appears most frequently in the string to the main function.
The main function should accept input of a string from the user and pass the string to the above function.
Output: The main function should then display the most frequently occurring character in the string which was returned to it from the called function.
Note/Hint : The ASCII character set (Appendix A of your book) contains 126 codes. You can set up an array of 126 counters and use the ASCII code of the character you are working with as an index to this array, incrementing the counter for that code. You should not need to type the codes into your program! Also note that you will not be able to use cin >> to get the string from the user because it only reads up to the first blank.
2. Case Manipulator – Write a program with three functions: upper, lower, and flip. The upper function should accept a C-string as an argument. It should step through all the characters in the string, converting each to uppercase. The lower function, too, should accept a C-string object as an argument. It should step through all the characters in the string converting, each to lowercase. Like upper and lower, flip should also accept a C-string. As it steps through the string, it should test each character to determine whether it is upper or lowercase. If upper, it should convert to lower. If lower, it should convert to upper.
The main function should accept one string from the user, then pass it to each of the functions.
Output: The original string, the uppercase, lowercase, and flipped case strings should all be displayed.
You should have two programs to turn in.
Explanation / Answer
1.
// C++ program to output the maximum occurring character in a string
#include<bits/stdc++.h>
#define ASCII_SIZE 256
using namespace std;
char getMaxOccuringChar(char* str)
{
// Create array to keep the count of individual characters
int count[ASCII_SIZE];
// Initialize the count array to zero
for (int j=0; j < ASCII_SIZE; j++)
count[j] = 0;
// Utility variables
int len = strlen(str);
int max = -1;
char c;
// Traversing through the string and maintaining the count of
// each character
for (int i = 0; i < len; i++) {
if (max < count[str[i]]) {
max = count[str[i]];
c = str[i];
}
}
return c;
}
// Driver program to test the above function
int main()
{
char* str = "sample string";
cout << "Max occurring character is "
<< getMaxOccuringChar(str);
}
2.