Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C: output most frequent word

Name: ludalex 2012-04-23 13:11

[HOMEWORK]
Hello, I have to make a C program to output the most used letter in a given string.

Here's what I've accomplished so far. It works fine, I guess, but I think there's a MUCH better way to write this algorythm.
Thanks in advance.


#include <stdio.h>
#include <stdlib.h>

struct alphabet {
    char letter;
    int times;
};

typedef struct alphabet Alphabet;

void main() {

char string[300];

    gets(string);


Alphabet Alph[300];

int i=0, j=0;

while (i<=strlen(string)) {

    while(j<=300) {

    if(string[i] != Alph[j].letter) {

        Alph[i].letter = string[i];
        Alph[i].times = 1;


    }
    else {

        Alph[j].times++;

        }
        j++;
        }

    j=0;
    i++;
    }



int y,max=0;
char letter_max[0];
for (y=0; y<strlen(string); y++) {

printf("Letter: %c, Times: %d \n", Alph[y].letter, Alph[y].times);

    if(Alph[y].times>max) {

        max=Alph[y].times;
        letter_max[0]=Alph[y].letter;
        }


}

printf("\n\n\t\tMost frequent letter: %c - %d times \n\n", letter_max[0], max);


}

Name: ludalex 2012-04-24 8:09

>>2
Doesn't work.
>>4
Yes, you're totally right.

Anyway, here's a different implementation:

void main()
{

int array[255] = {0}; // initialize all elements to 0

char str[] = "thequickbrownfoxjumpedoverthelazydog";

int i, max, index;

for(i = 0; str[i] != 0; i++)
{
   ++array[str[i]];
}


// Find the letter that was used the most
max = array[0];
index = 0;
for(i = 0; str[i] != 0; i++)
{
     if( array[str[i]] > max)
     {
         max = array[str[i]];
         index = i;
     }
}

printf("The max character is: %c \n", str[index]);

}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List