write a C Program Count the number of digits (0-9) from standard input, print th
ID: 3841263 • Letter: W
Question
write a C Program
Count the number of digits (0-9) from standard input, print the frequency of each digit, must use arrays. I have someof the code started. My program does not seem to add to the array count.
#include <stdio.h>
#define SIZE 10
int main(){
int digit[SIZE] = {0};
int i, x;
int c;
while( (c = getchar()) != EOF)
{
putchar(c);
for ( i = 0; i < SIZE; i++ ) {
if (c == i)
{
digit[i]++;
}
}
}
for ( i = 0; i < SIZE; i++ ) {
printf(" %d: %d", i, digit[i]);
}
}
Explanation / Answer
Mistakes you did in your code
1. Initialization
int digit[SIZE] = {0}; // this statement creates an array of name digit of size = SIZE =10.
This statement also initializes only the first element of array i,e. digit[0] = 0
If you want to initialize all the elements of this array you need to write as below
int digit[SIZE] = {0,0,0,0,0,0,0,0,0,0};
or
int digit[SIZE];
int i;
for(i=0;i<SIZE;i++){
digit[i]=0;
}
2. The another simple mistake is EOF, you cant directly write end of file using keyboard.
Try this code
#include <stdio.h>
#define SIZE 10
int main(){
int i;
int c=48;
int digit[SIZE];
//int digit[SIZE] = {0}; initializes only the first element of digit array i,e digit[0] = 0
//Hence Initializing all digit array elements with zero
for(int i=0;i<SIZE;i++){
digit[i] = 0;
}
//I have taken c range as [48,57] in ascii character which is similar to [0,9] in int as we can't type END OF FILE //(EOF) directly from key board
// This while loop terminates when we enter characters other than o to 9 from keyboard
while( c>=48 && c<=57 )
{
c = getchar();//
fflush(stdin);// we are flushing input device buffer so that it wont take the enter key character as input next time when //we use c = getchar()
putchar(c);
digit[c-48]++;// similar as digit[c]++
}
//Printing desired output
for ( i = 0; i < SIZE; i++ ) {
printf(" %d: %d", i, digit[i]);
}
}
Note: If you have any queries regarding this question, feel free to ask in comments.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.