im very new to C and got some questions about this part of a programm.
I know that this is counting letters but how does this work if you compare the variable c and 'a'.
c is zero and a would be decimal 97 in the ASCII code so no if statement would be true anyway?
if ( c >= 'a' && c <= 'z' ){
c-='a';
A[c] ;
Also what does A[c] ; do when there is only 1 element in the array int A[27] = {0}; ?
int c=0;
int A[27] = {0};
int main()
{
do{
if ( c >= 'a' && c <= 'z' ){
c-='a';
A[c] ;
}
else if ( c >= 'A' && c <= 'Z' ){
c-='A';
A[c] ;
}
else if (c == '\n'){
continue;
}
else{
A[26] ;
}
} while ((c = fgetc(data1)) != EOF);
for (c = 0; c < sizeof A / sizeof A[0] - 1; c )
{
printf("%c:d\t", c 'a', A[c]);
}
}```
CodePudding user response:
This code is not very good. You should use standard functions to detect letters.
int main(void)
{
int c;
size_t A[26] = {0};
while ((c = fgetc(stdin)) != EOF)
if(isalpha(c = toupper((unsigned char)c))) A[c - 'A'] ;
for (c = 0; c < sizeof A / sizeof A[0]; c )
printf("%c:%zu%c", c 'A', A[c], !((c 1) % 4) ? '\n' : '\t');
}
https://godbolt.org/z/jrTf751vW
CodePudding user response:
c >= 'a' && c <= 'z'
is testing whether c
contains a lower-case alphabetic character, which must be in the range of 'a' to 'z'. If c is less than 'a' the first test fails, if it is greater than 'z' the second test fails.
CodePudding user response:
Also what does A[c] ; do when there is only 1 element in the array int A[27] = {0};
In this array
int A[27] = {0};
there are 27 elements. The first element A[0] is explicitly initialized by zero and all other elements are implicitly initialized also by zero. So all elements are set to 0.
In the first iteration of the do-while loop the variable c
is equal to 0
int c=0;
So as the variable does not contain a letter (lower case or upper case) then the control will be passed to this else statement
else{
A[26] ;
}
That is all non-letter characters are countered in the element A[26] of the array.
If the variable c
contains a letter as for example 'a' then the index of the element of the array is calculated like c - 'a'
provided that all letters follows each other with the step equal to 1.
So the occurrence of the letter 'a' (or 'A' ) is calculated in the element A[0] of the array, the occurrence of the letter 'b' (or 'B') is calculated in the array element A[1] and so on due to these statements
c-='a';
A[c] ;
and
c-='A';
A[c] ;
Then the occurrences of letters are outputted in this for loop
for (c = 0; c < sizeof A / sizeof A[0] - 1; c )
{
printf("%c:d\t", c 'a', A[c]);
}
Pay attention to that in general it is not necessary that all letters follow each other with the step equal to 1. For example for the EBCDIC coding of characters this is not true.