I was given the following statement: Write a program that allows the user to enter positive integers (numbers entered should not be stored). At the end, report the number of times each digit (from 0 to 9) appeared in all the numbers. Example: If the user enters the numbers 1156, 23, 73364, 988, 1003, 5, it should be reported that 0 appeared 2 times, 1 appeared 3 times, 2 appeared 1 time, 3 appeared 4 times, etc.
I have the following code:
void cuentadigitos(int n, int digitos[])
{
for(int i = 0; i < 10; ++i) {
digitos[ i ] = 0;
}
n = abs(n);
while(n > 0) {
digitos[n % 10] += 1;
n /= 10;
}
for(int i = 0; i < 10; ++i) {
if (digitos[i] > 0 ) {
printf( "%d aparece %d veces.\n", i, digitos[i] );
}
}
}
int main(){
#define MAX 20
int numeros[MAX];
int n, ingreso;
cout << "cuantos num: " ; cin >> ingreso;
for (int i = 0; i < ingreso; i++){
cout << "Ingrese numeros: "; cin >> n;
cuentadigitos(n, numeros);
}
return 0;
}
Example of what it returns:
how many num: 2
Enter numbers: 469
4 appears 1 times.
6 appears 1 times.
9 appears 1 times.
Enter numbers: 112
1 appears 2 times.
2 appears 1 times.
The code "fulfills" its function, but what I want to achieve is first to enter all the numbers, and to count the digits that appear in all the entered ones, not one by one. what should I correct? From already thank you very much!!
You just add an array where you store the numbers, read them first, and then call the function with each one.
The problem that the previously counted digits do not accumulate is because each time you call the function you set each element of the array to 0:
You will only have to initialize the array, you can do it with that same code but at the beginning of the main function where it is executed only once or you can use a list initializer:
By the way, you can create a type variable
unsigned int
so that it only allows positive numbers. I also don't think you want to print the number of digits each time you call the function so you can move that part somewhere else.I also suggest that you be consistent and use all C++ features, unless it doesn't have a similar feature. For example,
cout
what is from C++ andprintf
what is from C, both are used to print to the console.The code would look like this.
You can try it here .