Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find maximum occurrence of character in a string
In C programming, finding the character with maximum occurrence in a string involves counting the frequency of each character and determining which appears most often. This is useful for text analysis and character statistics.
Syntax
int frequency[ASCII_SIZE];
while(string[i] != '\0') {
frequency[(int)string[i]]++;
i++;
}
Algorithm
The algorithm to find maximum occurrence follows these steps −
- Initialize a frequency array to count occurrences of each ASCII character
- Traverse the string and increment frequency count for each character
- Find the character with maximum frequency count
Example: Complete Program
Here is a complete C program to find the character with maximum occurrence in a string −
#include <stdio.h>
#include <string.h>
#define CHARS 256
int main() {
char string[] = "tutorials point";
int frequency[CHARS] = {0};
int i, maximum = 0;
printf("Input string: %s<br>", string);
/* Count frequency of each character */
for (i = 0; string[i] != '\0'; i++) {
frequency[(int)string[i]]++;
}
/* Find character with maximum frequency */
for (i = 0; i < CHARS; i++) {
if (frequency[i] > frequency[maximum]) {
maximum = i;
}
}
printf("Maximum occurrence character is '%c' = %d times<br>",
maximum, frequency[maximum]);
return 0;
}
Input string: tutorials point Maximum occurrence character is 't' = 3 times
Example: Interactive Version with User Input
This version allows user to input their own string −
#include <stdio.h>
#include <string.h>
#define SIZE 100
#define CHARS 256
int main() {
char string[SIZE];
int frequency[CHARS] = {0};
int i, maximum = 0;
printf("Enter a string: ");
fgets(string, SIZE, stdin);
/* Remove newline if present */
string[strcspn(string, "<br>")] = '\0';
/* Count frequency of each character */
for (i = 0; string[i] != '\0'; i++) {
frequency[(int)string[i]]++;
}
/* Find character with maximum frequency */
for (i = 0; i < CHARS; i++) {
if (frequency[i] > frequency[maximum]) {
maximum = i;
}
}
printf("Maximum occurrence character is '%c' = %d times<br>",
maximum, frequency[maximum]);
return 0;
}
Key Points
- The frequency array size should be 256 to handle all ASCII characters
- Initialize the frequency array to zero before counting
- Use
fgets()instead ofgets()for safe input handling - Time complexity is O(n) where n is the string length
- Space complexity is O(1) as the frequency array size is constant
Conclusion
Finding the maximum occurring character in C requires counting character frequencies and identifying the maximum. This approach efficiently handles all ASCII characters with linear time complexity.
Advertisements
