Why does the code I commented out does not work to count the digits 0-9? for example when the input is happy 34567 fans#. The number counter should be 5 and letter counter should be 9.
#include <stdio.h>
int main()
{
/*edit*/
/* Write your code here */
char ch;
int letter_counter=0, num_counter=0;
printf("Enter your characters (# to end):\n");
while((ch = getchar()) != '#'){
//if( ('A'<=ch<='Z') || ('a'<= ch <= 'z')){
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')){
letter_counter ;
}
//else if('0' <=ch <= '9'){
else if(ch >= '0' && ch <= '9') {
num_counter ;
}
}
printf("The number of digits: %d\n", num_counter);
printf("The number of letters: %d", letter_counter);
/*end_edit*/
return 0;
}
CodePudding user response:
The expressions
'0' <=ch <= '9'
and
'A' <= ch <= 'Z'
and
'a' <= ch <= 'z'
will all evaluate to true, irrespective of the value of ch
.
According to the rules of operator precedence, the expression
'A' <= ch <= 'Z'
is equivalent to:
('A'<=ch) <= 'Z'
The sub-expression 'A'<=ch
will evaluate to either true (1
) or false (0
), so the entire expression will be equivalent to either
0 <= 'Z'
or:
1 <= 'Z'
Assuming that you are using an ASCII-compatible character set, 'Z'
will have the character code 90
, so the entire expression will be equivalent to either
0 <= 90
or:
1 <= 90
In both cases, the expression will evaluate to true.
That is why you must write
ch >= 'A' && ch <= 'Z'
or
'A' <= ch && ch <= 'Z'
instead of:
'A' <= ch <= 'Z'
Also, it is worth noting that you can simplify your code a bit, by using the functions isalpha and isdigit. Both of these functions require you to #include <ctype.h>
.
#include <stdio.h>
#include <ctype.h>
int main()
{
int ch;
int letter_counter=0, digit_counter=0;
printf( "Enter your characters (# to end):\n" );
while ( (ch=getchar()) != '#') {
if ( isalpha( ch ) ) {
letter_counter ;
}
else if ( isdigit( ch ) ) {
digit_counter ;
}
}
printf( "The number of digits: %d\n", digit_counter);
printf( "The number of letters: %d\n", letter_counter);
return 0;
}
CodePudding user response:
you could do it like that :
#include <stdio.h>
int main()
{
char ch;
int letter_counter=0, num_counter=0;
printf("Enter your characters (# to end):\n");
while((ch = getchar()) != '#'){
if (ch >= 'a' && ch <= 'z')
letter_counter = 1;
if (ch >= 'A' && ch <= 'Z')
letter_counter = 1;
if (ch >= '0' && ch <= '9')
num_counter = 1;
}
printf("The number of digits: %d\n", num_counter);
printf("The number of letters: %d", letter_counter);
return 0;
}