-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_set2a.c
113 lines (90 loc) · 2.19 KB
/
problem_set2a.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <cs50.h>
#include <stdio.h>
#include <string.h> //for strlen()
#include <math.h>
#include <ctype.h> //for isalpha()
int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
int CL_index(int l, int w, int s);
int main(void)
{
//get sample text from user
string text = get_string("Text: ");
//calculate index
int letters = count_letters(text);
int words = count_words(text);
int sentences = count_sentences(text);
int index = CL_index(letters, words, sentences);
//print grade level of text
if (index >= 16)
{
printf("Grade 16+\n");
}
else if (index < 1)
{
printf("Before Grade 1\n");
}
else
{
printf("Grade %i\n", index);
}
}
//counts numbers of letters in string
//measured using isalpha
int count_letters(string text)
{
int length = strlen(text);
int counter = 0;
for (int i = 0; i < length; i++)
{
if (isalpha(text[i]))
{
counter++;
}
}
return counter;
}
//counts number of words in string
//measured by counting number of spaces, then adding 1
int count_words(string text)
{
int length = strlen(text);
int counter = 0;
for (int i = 0; i < length; i++)
{
if (text[i] == ' ')
{
counter++;
}
}
return counter + 1; //add 1 because we have not yet counted the final word in text
}
//counts number of sentences in string
//measured by number of . ! or ? in string
int count_sentences(string text)
{
int length = strlen(text);
int counter = 0;
for (int i = 0; i < length; i++)
{
char c = text[i];
if (c == '.' || c == '!' || c == '?')
{
counter++;
}
}
return counter;
}
//calculate Coleman-Liau index
//inputs are number of letters, words and sentences in text
int CL_index(int l, int w, int s)
{
//calculate average number of letters per 100 words
float L = (float) l / (float) w * 100 ;
//calculate average number of sentences per 100 words
float S = (float) s / (float) w * 100 ;
//calculate index
int index = round(0.0588 * L - 0.296 * S - 15.8);
return index;
}