DEV Community

Pranav Madhavan
Pranav Madhavan

Posted on • Edited on

CS50 Problem Set 2 , Readability

//CS50 Problem Set 2 (Fall 2022): Readability
//Author: Pranav Madhavan

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

int count_letters(string text, int str);
int count_words(string text, int str);
int count_sentences(string text, int str);

int main(void)
{
    //ask user for string and store in s
    string s = get_string("Text: ");
    //find length of a string using srlen function
    int strl = strlen(s);

    int letters = count_letters(s, strl);  //count of Letters
    int words = count_words(s, strl);  //count of Words
    int sentences = count_sentences(s, strl);  //count of sentences

    float L = 100 * (float) letters / (float) words;//Letters Per Hundred words
    float S = 100 * (float) sentences / (float) words; //Sentences Per Hundred Words

    int index = round(0.0588 * L - 0.296 * S - 15.8); //Coleman-Liau index


    //to print grade
    if (index < 1)
    {
        printf("Before Grade 1\n");
    }
    else if (index < 16)
    {
        printf("Grade %i\n", index);
    }
    else
    {
        printf("Grade 16+\n");
    }

}

//function to count number of letters.
int count_letters(string text, int str)
{

    //variable which stores no of Letters.
    int l = 0;

    for (int i = 0; i < str; i++)
    {

        if (isalpha(text[i]) != 0)
        {
            l++;
        }
    }
    return l;
}

int count_words(string text, int str)
{
    //count of spaces.
    int w = 0;

    for (int i = 0; i < str; i++)
    {
        if (isspace(text[i]) != 0)
        {
            w++;
        }
    }

    //no of words.
    w = w + 1;
    return w;
}

int count_sentences(string text, int str)
{
    //count of sentences
    int s = 0;
    //count of . ! and ?
    for (int i = 0; i < str ; i++)
    {
        if (text[i] == 33 || text[i] == 46 || text[i] == 63)
        {
            s++;
        }
    }

    return s;

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)