How to find the number of occurrences (frequency) of each digit in a random number in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h> 
#include <time.h> 

int getRandom(int lower, int upper) { 
    return rand() % (upper - lower + 1) + lower; 
} 

void digitsCounter(int n, int arr[]) {
	while (n) {
        arr[n % 10]++;
		n /= 10;
    }
}
  
int main()
{
	srand(time(NULL)); 
	int arr[10] = {0}, n = getRandom(1000000, 9999999);
	
    digitsCounter(n, arr);
	for (int i = 0; i < 10; i++) {
        if (arr[i] != 0)
			printf("digit:%d - %d times\n", i, arr[i]);
	}
       
    return 0;
}
  
  
  
/*
run:
  
digit:0 - 1 times
digit:1 - 2 times
digit:2 - 1 times
digit:3 - 1 times
digit:7 - 1 times
digit:9 - 1 times
    
*/

 



answered Jul 4, 2020 by avibootz
...