Home > Blockchain >  Count times digits appear in a number C
Count times digits appear in a number C

Time:10-27

I am trying to make a code in C that takes a number as an input, counts how many times 0-9 appears in the given number. The code as nooby as it might is:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num,dig,dat[9],mod;

    printf("Give a number: ");
    scanf("%d",&num);

    mod = num % 10;


  while(mod != 0)
    {

      if(mod > 1)
      {
          dig = mod / 10;

          while(dig >= 0 )
          {
                dat[dig];

          }
      }
      else if(mod =1)
      {
          dig = mod/1;

           while(dig >= 0 )
          {
                dat[dig];

          }

      }
      --mod;

    }
      printf("%d appears %d\n",dig,dat[dig]);


    return 0;
}

Thanks in advance

Nothing really works, i dont even get any response from printf.

CodePudding user response:

#include <stdio.h>

int main(void) {
    int n = 12334268;
    int digits[10] = {0};
    
    while(n)
    {
          digits[n];
        n/=10;
    }
    
    for(int i=0; i<10;   i)
    {
        if (digits[i])
        {
            printf("Digit %d appears %d times\n", i, digits[i]);
        }
    }
    
    return 0;
}

Output

Success #stdin #stdout 0s 5512KB
Digit 1 appears 1 times
Digit 2 appears 2 times
Digit 3 appears 2 times
Digit 4 appears 1 times
Digit 6 appears 1 times
Digit 8 appears 1 times

CodePudding user response:

For starters the array dat shall have 10 elements because there are 10 digits 0-9.

dat[10],

And moreover you are using the uninitialized array

  dat[dig];

If the entered number is divisible by 10 then the while loop is skipped

mod = num % 10;


while(mod != 0)
{
   //...

So the code does not make sense.

Pay attention to that you should deal with unsigned integers. Otherwise the program shall take into account the sign of the entered number.

Also the user can enter 0 that is a valid number containing one digit 0.

The program can look the following way.

#include <stdio.h>

int main( void )
{
    enum { N = 10 };
    unsigned int digits[N] = { 0 };

    unsigned int num;

    printf( "Give a number: " );

    if ( scanf( "%u",&num ) == 1 )
    {
        const unsigned int Base = 10;
        do
        {
              digits[num % Base];
        } while ( num /= Base );

        puts( "The number contains the following digits:" );
        for ( unsigned int i = 0, j = 0; i < N; i   )
        {
            if ( digits[i] != 0 )
            {
                if ( j != 0 ) printf( ", " );
                printf( "%u: %u", i, digits[i] );
                j = 1;
            }
        }
    }
}
  • Related