Sorry I'm late, but here's one way to do it. I hope the comments help:
Code:
/* count.c
*
* Count the occurance of each numeral in a string.
*/
#include <stdio.h>
int main( void )
{
/* When we count up the frequency of each number, we'll store it in
* this array. The array is initialized to zero.
*/
int total[10] = { 0 };
/* We'll use a character pointer to move through our string later. */
char *pointer;
/* Get the number from the user. We'll limit the number length to 51,
* which allows 50 digits and room for the terminating null.
*/
char number[51];
puts( "Enter an integer:" );
/* Using fgets() instead of gets() helps avoid buffer overflows. */
fgets( number, 51, stdin );
/* Loop through the number a single time, counting the frequency
* of each digit, 0-9.
*
* The 'for' loop is initialized by pointing the character pointer to the
* beginning of 'number' (its address). We continue the loop as long
* as the pointer references something other than a zero (the null at
* the end of the string is a zero, not to be confused with the
* character '0' the user might provide). Finally, we increment the
* pointer across the string on each iteration.
*/
for ( pointer = number; *pointer; pointer++ )
{
/* I'm not sure if you've learned about switch...case in class yet,
* so I hope this is okay.
*/
switch( *pointer )
{
case '0': total[0]++; break;
case '1': total[1]++; break;
case '2': total[2]++; break;
case '3': total[3]++; break;
case '4': total[4]++; break;
case '5': total[5]++; break;
case '6': total[6]++; break;
case '7': total[7]++; break;
case '8': total[8]++; break;
case '9': total[9]++; break;
}
}
/* Display the final count. I split it across two printf()'s
* purely for aethetics. One would certainly do the trick.
*/
printf( "0: %d\n1: %d\n2: %d\n3: %d\n4: %d\n",
total[0], total[1], total[2], total[3], total[4] );
printf( "5: %d\n6: %d\n7: %d\n8: %d\n9: %d\n",
total[5], total[6], total[7], total[8], total[9] );
return 0;
}
Sample output:
Code:
Enter an integer: 8675309 - Jenny don't lose my number!
0: 1
1: 0
2: 0
3: 1
4: 0
5: 1
6: 1
7: 1
8: 1
9: 1
The
switch...case works to ignore non-numbers without allowing it to break the code.