I am brand new to writing my own code. I just started the CS50x intro class and have so far made it to pset 2 readability. It's getting easier to understand what's going on. I just wanted to get some opinions on the code that I wrote to see if there were possible improvements/changes that I could make.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
//initialize lenght function
int length(string str, char check);
int main(void)
{
//Get user input
string input = get_string("Text: ");
//Calculate and set grade level. Take user input and run it thorugh the lenght function. l for letters, w for words and s for sentances.
float gradeLevel = (0.0588 * (100 * (float) length(input, 'l') / (float) length(input, 'w')) - 0.296 * (100 * (float) length(input, 's') / (float) length(input, 'w'))) - 15.8;
//output grade level
if (round(gradeLevel) >= 16)
{
printf("Grade 16+\n");
}
else if (round(gradeLevel) < 1)
{
printf("Before Grade 1\n");
}
else
{
printf("Grade %i\n", (int) round(gradeLevel));
}
//print lengths for testing
/*
printf("%i letter(s)\n", length(input, 'l'));
printf("%i word(s)\n", length(input, 'w'));
printf("%i sentance(s)\n", length(input, 's'));
*/
}
//function to get length of letters, words and sentences
int length(string str, char check)
{
int letterCount = 0;
int wordCount = 1;
int senCount = 0;
int n = strlen(str);
//check letter count
if (check == 'l')
{
for (int i = 0; i < n; i++)
{
if (isalpha(str[i]))
{
letterCount++;
}
}
return letterCount;
}
//check word count
else if (check == 'w')
{
for (int i = 0; i < n; i++)
{
if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
{
wordCount++;
}
}
return wordCount;
}
//check sentance count
else if (check == 's')
{
for (int i = 0; i < n; i++)
{
if (str[i] == '.' || str[i] == '!' || str[i] == '?')
{
senCount++;
}
}
return senCount;
}
return 0;
}
Thank you for the detailed feedback. Here's the specs of the program
Your program should count the number of letters, words, and sentences in the text. You may assume that a letter is any lowercase character from a to z or any uppercase character from A to Z, any sequence of characters separated by spaces should count as a word, and that any occurrence of a period, exclamation point, or question mark indicates the end of a sentence.
Your program should print as output "Grade X" where X is the grade level computed by the Coleman-Liau formula, rounded to the nearest integer.
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".
The algorithm used was the Coleman-Liau index