View Single Post
Old 01-12-2007, 08:48 AM   #5 (permalink)
Tyrell
Upright
 
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.
Tyrell is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73