The below code reads in a file and then counts the number of ‘a’, ‘b’, etc… characters, it counts both ‘A’ and ‘a’ as the same letter.
The code below works; however if I change the declaration of the int array count[26] = {0} to count[25] = {0} (and ONLY change this), the program will not properly store the number of ‘z’ characters, which is stored in the 25th element of the array. It will store -1 in the 25th element. I don’t understand why? I never access count[26], only count[0] through count[25], but why must I add one more element to the array for the code to work? When count is 26 elements long the correct number of ‘z’ characters is stored in count[25].
int main (int argc, char *argv[], char **env)
{
// Declare variables
int c, big ;
int count[26] = {0} ;
int bar[25] = {0} ;
ifstream infile("histo.data") ;
while (!infile.eof())
{
c = infile.get() ;
c = tolower(c) ;
if ( c >= 97 && c <= 122)
{
count[c - 'a']++ ;
}
}
infile.close() ;
for (int i = 0; i <= 25; i++)
{
printf("%c: %d\n",(97+i),count[i]) ;
}
// find largest letter count
big = count[0] ;
for (int i = 1; i <= 25; i++)
{
if(count[i] > big)
{
big = count[i] ;
}
}
// bar lengths
int cols = atoi(getenv("COLUMNS")) ;
for (int i = 0; i <= 25; i++)
{
bar[i] = (cols-3)*count[i]/big ;
}
// print bars
for (int i = 0; i <= 25; i++)
{
printf("\n%c: ",(97+i));
for (int j = 1; j <= bar[i]; j++)
{
cout << "=" ;
}
}
cout << "\n" << endl ;
}
Arrays are zero indexed, however the number you declare them with is the size of the array. Therefore, if you want 26 items, you need to declare an array of 26. The index range is 0…25 though.