Please tell me whats wrong in code the output is 00000000.
I know there is some mistake but cant find it.
#include <stdio.h>
#include <string.h>
int main()
{
int c=0;
char s[100];
fgets(s, 100, stdin);
printf("%s", s);
for(int i=0;i<=9;i++)
{
for(int j=0;j<strlen(s);j++)
{
if(s[j]==i){
c++;
}
}
printf("%d", c);
}
return 0;
}
Firstly, you are comparing a character with a int. Have a look at Char to int conversion in C for a solution.
Then, I would remember you that "0" is index 48 in ASCII table, not 0 : http://www.asciitable.com/
The key problem is
s[j]==i
. That compares achar
of the string to the values 0 to 9 ratter than tochar
'0'
to'9'
.Another is the
c
is not reset to zero each loop.Instead of looping 10 times, test if the
char
is a digit.Instead of calling
j<strlen(s)
repeatedly, just test ifs[j] == 0
Code uses
size_t
rather thanint
as a string's length is limited tosize_t
- which may exceedint
in extreme cases. Either work OK work size 100.isdigit()
declared in<ctype.h>
(unsigned char)
used asisdigit()
expect a value in the(unsigned char)
andEOF
and achar
may be negative.Various style choices - all function the same.
"Given a string consisting of alphabets and digits" is a minor contraction. In C, a string includes the final null character: "A string is a contiguous sequence of characters terminated by and including the first null character" C11 §7.1.1 1. Yet folks often speak colloquially as is the null character was not part of the string.