how to compare unknown elements of an array in c++?

Sorry for bad English .
I was trying to write a program that gets a number and see if the digits of an entered number are repeated or not . I did try to if(analyse[0]==analyse[1]==analyse[2]==…) but since I don’t know exactly how many elements will array have, it didn’t work

#include<iostream>
int main(){
    int number,number_help;
    const int count{10};
    std::cin>>number;
    number_help = number ;
    int digitcount{0};
    while(number_help>0){
        number_help/=10;
        digitcount+=1;
    }
    int analyse[count]{};
    for(size_t i {0}; i<digitcount ; i++){
        analyse[i] = number%10;
        number/=10;
    }
    //I don't know what to code here
    return 0;
}

>Solution :

Change your approach: count how many there are of each digit instead of comparing them to each other.
This is much simpler.

Example:

#include<iostream>

int main(){
    int number;
    std::cin >> number;
    const int count{10};
    int frequency[count]{};
    do {
        frequency[number % 10] += 1;
        number /= 10;
    } while (number != 0);
    for (int i{0}; i < count; i++) {
        if (frequency[i] > 1) {
            std::cout << i << " was repeated " << frequency[i] << " times.\n";
        }
    }
}

Leave a Reply