I'm trying to make a program that verifies if a number meets two requirements:
the number has 4 digits
not all the digits are the same
I've been made it, and it looks good, but the code fails in a specific case.
When the user enters a number with all of the digits equal, like 1111
, the first time the program will say that this number isn't correct and will ask for a new number, but if the user enters another invalid number with all digits equal, like 2222
, the verification fails and accepts this new number as a valid number.
I don't know what the problem could be, can someone help?
This is the code:
#include <iostream>
using namespace std;
int main(){
int n; // number
cout << "enter a 4-digit number with at least one different digit number: ";
cin >> n;
int m = 0, o = 0, u = n, z = 0; // variables
int counter, counter1, counter2 = 5; //counters
int x[4], y[4]; // vectors
//--------------------------- verification -------------------------------------
while(counter != 4 && counter2 > 3){
// ======= number size verification =======
while (u > 0){
u = u/10;
counter = counter + 1; // number digit counter
}
if(counter != 4){ // if the number has less than 4 digits
cout << "the number has less than 4 digits, enter a valid number: ";
cin >> n;
u = n;
}
// =================================================
// ========= check repetead numbers ================
if(counter == 4){ // if the number has 4 digits
u = n;
z = n;
for(int i = 3; i >= 0; i--){ // convert the number into two vectors
u = u % 10;
x[i] = u;
y[i] = u;
z = z / 10;
u = z;
}
counter2 = 0; // repetition counter 2 (reset counter value)
// traversal of the vector in search of repeated numbers
for(int j = 0; j < 4; j++){
counter1 = 0; // repetition counter 1 (reset counter value)
m = x[j];
for(int k = 0; k < 4; k++){
o = y[k];
if(m == o){
counter1 = counter1 + 1; // if there are repeated numbers counter increases
y[k] = 0; // delete that vector position
}
}
if(counter1 == 1 || counter1 == 0){ // if only found the repetition of the same box
counter1 = 0; // reset counter1
}else{
counter2 = counter2 + counter1; // if not, its value is assigned to counter2
}
}
}
if(counter2 == 4){ // if the number has all its digits the same
n = 0;
cout << "the number has all its digits the same, enter a valid number: ";
cin >> n;
}
}
cout << "valid number";
return 0;
}
image of the failure:
To check if your number is 4 digits you can simply compare it:
if( n < 1000 or n > 9999 ) // not 4 digits number
To check if all digits are the same, just check if it is divisible by 1111 (thanks to @SamVarshavchik )
if( n % 1111 == 0 ) // all digits are the same