I have the following code to count the occurrences of each letter in an input string. The while loop executes correctly. Now I have arr[]
containing the number of 'a's in arr[0]
, 'b's in arr[1]
and so on.
However, the following printf
does not display the complete contents of arr
. (Sample o/p given below).
If I comment out the while loop altogether, printf
prints all 26 arr[]
values fine!
What could I be missing in this simple program?
If it is of any help, I am using VS 2008.
int arr[26]={'\0'};
int i = 0, c = 0, idx = 0, count = 0;
while( (c = getchar()) != EOF ) {
if( 'a' <= c && 'z' >= c ) {
idx = c - 'a';
arr[idx] = arr[idx]+1;
}
}
for(count = 0; count < 26; count++) {
printf("arr[%d] = %d\n", count, arr[count]);
}
The outputs that I get (keeps varying for different inputs):
abcxyz
arr[0] = 1
arr[1] = 1
^CPress any key to continue . . .
abcabc
arr[0] = 2
arr[1]
^CPress any key to continue . . .
@Nobilis: Updated code to account for Uppercase letters, also made the print more meaningful :)
int main()
{
int arr[26]={'\0'};
int i = 0, c = 0, idx = 0, count = 0;
while( (c = getchar()) != EOF )
{
if( 'a' <= c && 'z' >= c )
{
idx = c - 'a';
arr[idx] = arr[idx]+1;
}
if( 'A' <= c && 'Z' >= c )
{
idx = c - 'A';
arr[idx] = arr[idx]+1;
}
}
for(count = 0; count < 26; count++)
{
printf("%c or %c = %d\n", ('A'+count), ('a'+count), arr[count]);
}
}