View Single Post
Old Nov 15th, 2005, 9:32 AM   #6
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
The reason I suggest division and the modulus operator is because your post specifies "numbers". If you use a string, then you'll have to validate it first, which somewhat tosses the "easiest" description. If you acquire the information using scanf, you'll get validation or failure as part of the package. Counting the occurrence of a digit with division/modulus is every bit as simple as counting with a pointer.
#include <stdio.h>
#include <stdlib.h>

int failure (char *why)
{
    fprintf (stderr, "%s\n", why);
    return 1;
} 
int main (int argc, char *argv [])
{
    int theNumber;
    int theDigit;
    int count = 0;

    // Getting and validating input
    printf ("Enter a number: ");
    if (scanf ("%d", &theNumber) != 1) return failure ("Not a number");
    theNumber = abs (theNumber);
    printf ("Enter a single digit: ");
    if (scanf ("%d", &theDigit) != 1) return failure ("Not a number");
    theDigit = abs (theDigit);
    if (theDigit > 9) return failure ("Too many digits"); 

    // Counting digits
    while (theNumber)
    {
        if ((theNumber % 10) == theDigit) count++;
        theNumber /= 10;
    }

    // Presenting results
    printf ("The digit %d occurs %d times\n", theDigit, count);
    rewind (stdin);
    getchar ();
    return 0;
}
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote