Search code examples
cfunctionprogram-entry-pointcs50function-prototypes

How can I use the values from function prototypes inside the main function? - Combining separate values


So my task was about assessing the reading level of a text prompt. In the following code I already managed to analyze the text in three ways. No. of letters, words and sentences. In order to calculate the reading level, however, I need to combine the values into a formula:

"index = 0.0588 * L - 0.296 * S - 15.8

where L is the average number of letters per 100 words in the text, and S is the average number of sentences per 100 words in the text.

("Modify readability.c so that instead of outputting the number of letters, words, and sentences, it instead outputs the grade level as given by the Coleman-Liau index (e.g. "Grade 2" or "Grade 8"). Be sure to round the resulting index number to the nearest whole number!

If the resulting index number is 16 or higher (equivalent to or greater than a senior undergraduate reading level), your program should output "Grade 16+" instead of giving the exact index number. If the index number is less than 1, your program should output "Before Grade 1".")

So yeah, basically I have all the values needed, but I don't know how to use them for the formula to calculate the final value because they are all inside the function prototypes, and I can't get them together in the main fucntion...

#include <ctype.h>
#include <string.h>
#include <cs50.h>
#include <stdio.h>
#include <math.h>

int count_letters(string letters);
int count_words(string words);
int count_sentences(string sentences);

int main(void)
{
    string text = get_string("Text: ");
    count_letters(text);
    count_words(text);
    count_sentences(text);
}

int count_letters(string letters)
{
    int count = 0;
    for (int i = 0; i < strlen(letters); i++)
    {
        if (isalpha(letters[i]) != 0)
        {
            count++;
        }
    }
    printf("%i letter(s)\n", count);
    return count;
}

int count_words(string words)
{
    int count_w = 0;
    for (int j = 0; j < strlen(words); j++)
    {
        if (isspace(words[j]) != 0)
        {
            count_w++;
        }
    }
    count_w++;
    printf("%i word(s)\n", count_w);
    return count_w;
}

int count_sentences(string sentences)
{
    int count_s = 0;
    for (int k = 0; k < strlen(sentences); k++)
    {
        if ((int) sentences[k] == 33)
        {
            count_s++;
        }
        if ((int) sentences[k] == 46)
        {
            count_s++;
        }
        if ((int) sentences[k] == 63)
        {
            count_s++;
        }
    }
    printf("%i sentence(s)\n", count_s);
    return count_s;
}



Solution

  • You need to use the values that are returned by the functions.

    int total_letters = count_letters(text);

    ...and so on. After you have all three, you can calculate the number of letters per 100 words, and use the equation to calculate the grade level.