-3

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;
}
Mhz_rkx
  • 1
  • 1
  • `analyse` always has 10 elements. Anyway, `a == b == c` doesn't do what you think is does. [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should help. – Evg Jan 25 '23 at 15:22
  • 1
    If `count` is an integral constant initialized with a literal (`10`, here), the code is OK - `count` [can be used as a constant expression](https://stackoverflow.com/questions/45593044/the-value-of-a-const-variable-is-or-is-not-usable-in-a-constant-expression-depe). – Evg Jan 25 '23 at 15:25
  • 1
    @SamVarshavchik What's wrong with `int analyse[count]{};`? `count` is a constant expression. – NathanOliver Jan 25 '23 at 15:26
  • Bit off-topic, but if you would use [std::vector](https://en.cppreference.com/w/cpp/container/vector) instead of "C" style array for analyse you don't have to precalculate its size, you can just push_back more numbers. std::vector is the type to use when you don't know array sizes up front. – Pepijn Kramer Jan 25 '23 at 15:28
  • you know how to write a loop, you know how to comapre two elements for equality. Thats basically all you need to compare all elements of the array for equality – 463035818_is_not_an_ai Jan 25 '23 at 15:29
  • 1
    Input the number as a string. Much easier to compare and count digits. – Thomas Matthews Jan 25 '23 at 15:57

1 Answers1

0

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";
        }
    }
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82