Noah210012 Noah210012 - 20 days ago 5
C Question

Error in C Program (not fully exiting loop?)

Okay, so this program is supposed to read the digits of a number entered by the user and check for repeated digits. The program keeps asking for numbers until the user enters anything less than or equal to 0. It mostly works in the sense that if you enter a repeated digit, it will tell you. However if you enter the same digit from another number call, it is considered a repeat digit. For example, if 23 is entered in the one instance and then 52 is entered in another, it considers there to be a duplicate (even though there isn't in the new number entered). Any ideas on how to fix it?

#include <stdio.h>
#include <stdbool.h> //as per C99 standard


int main (void)
{

bool digit_seen[10] = {false};
int digit;
long n;

while (1){

printf("Enter a number (enter 0 to terminate the program): ");
scanf("%ld", &n);

if (n == 0){
break;
}

while (n > 0){
digit = n % 10;

if (digit_seen[digit]){
break;
}

digit_seen[digit] = true;
n /= 10;
}

if (n > 0){
printf("Repeated digit\n");
} else {
printf("No repeated digit\n");
}
}

return 0;


}

Answer

However if you enter the same digit from another number call, it is considered a repeat digit.

As it stands, digit_seen was initialised only once and outside the while loop, it was never reinitialised for new input n.

You will need to move this code bool digit_seen[10] = {false}; to inside your while loop. That would fix the issue.

Comments