Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading