Write a C program to find the frequency characters in a string using recursion.
#include <stdio.h>
#include <string.h>
/* calculates the frequency of characters in the given string */
void calcFrequency(char *str, int *freq) {
int index;
if (*str != '\0') {
index = *str - 'a';
freq[index]++;
calcFrequency(str + 1, freq);
}
return;
}
int main() {
char str[256];
int i, frequency[26];
/* get the input string from the user */
printf("Enter your input string(only lowercase):");
fgets(str, 256, stdin);
str[strlen(str) - 1] = '\0';
/* fill frequency with 0s */
memset(frequency, 0, sizeof(frequency));
/* finds the frequency of characters in the given string */
calcFrequency(str, frequency);
printf("Frequency of characters:\n");
/* prints the result */
for (i = 0; i < 26; i++) {
if (frequency[i]) {
printf("%c => %d\n", i + 'a', frequency[i]);
}
}
#include <string.h>
/* calculates the frequency of characters in the given string */
void calcFrequency(char *str, int *freq) {
int index;
if (*str != '\0') {
index = *str - 'a';
freq[index]++;
calcFrequency(str + 1, freq);
}
return;
}
int main() {
char str[256];
int i, frequency[26];
/* get the input string from the user */
printf("Enter your input string(only lowercase):");
fgets(str, 256, stdin);
str[strlen(str) - 1] = '\0';
/* fill frequency with 0s */
memset(frequency, 0, sizeof(frequency));
/* finds the frequency of characters in the given string */
calcFrequency(str, frequency);
printf("Frequency of characters:\n");
/* prints the result */
for (i = 0; i < 26; i++) {
if (frequency[i]) {
printf("%c => %d\n", i + 'a', frequency[i]);
}
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string(only lowercase):helloworld
Frequency of characters:
d => 1
e => 1
h => 1
l => 3
o => 2
r => 1
w => 1
Enter your input string(only lowercase):helloworld
Frequency of characters:
d => 1
e => 1
h => 1
l => 3
o => 2
r => 1
w => 1
No comments:
Post a Comment