Skip to content

Instantly share code, notes, and snippets.

@iboss-ptk
Created November 27, 2022 03:57
Show Gist options
  • Save iboss-ptk/84c04facd1bbdcb41fb9c6c4eee86f88 to your computer and use it in GitHub Desktop.
Save iboss-ptk/84c04facd1bbdcb41fb9c6c4eee86f88 to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int count_sentences(string text);
int count_words(string text);
int count_letters(string text);
int main(void)
{
string text = get_string("Text: ");
// get infos from text for calculating Coleman-Liau index
int sentence_count = count_sentences(text);
int word_count = count_words(text);
int letter_count = count_letters(text);
// calculate Coleman-Liau index
float L = ((float)letter_count / (float)word_count) * 100.0;
float S = ((float)sentence_count / (float)word_count) * 100.0;
int index = (int)(round(0.0588 * L - 0.296 * S - 15.8));
// check index and print result accordingly
// U.S. Grade system has only 1-16
if (index < 0)
{
printf("Before Grade 1");
}
else if (index >= 16)
{
printf("Grade 16+");
}
else
{
printf("Grade %d", index);
}
printf("\n");
}
int count_sentences(string text)
{
int sentence_count = 0;
for (int i = 0; i < strlen(text); i++)
{
// '.', '!', '?' are sentence ending indicators
if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
sentence_count++;
}
}
return sentence_count;
}
int count_words(string text)
{
// starts with 1 word since it counts ' '
// so if the input is "Congrats!"
// there is no space but still count as 1 word
// and assume that input always have atleast 1 word
int word_count = 1;
for (int i = 0; i < strlen(text); i++)
{
// assumes no multiple consecutive spaces
// assumes no spaces at the start or the end of text
if (text[i] == ' ')
{
word_count++;
}
}
return word_count;
}
int count_letters(string text)
{
int letter_count = 0;
for (int i = 0; i < strlen(text); i++)
{
// count only if within 'a-z' or 'A-Z' ASCII range
if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z'))
{
letter_count++;
}
}
return letter_count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment