Alex Alex - 1 month ago 9
C Question

finding a repeating integer in an array

Hi managed to make my program checked if i have repeated 8's. I also want to print out how many repeated 8's i have stored in the array.

#include <stdio.h>
#include <stdbool.h>
int main(void)
{
bool digit_seen[10] = {false};
int digit=0;
long n;

printf("Enter number: ");
scanf("%ld", &n);

while (n>0)
{
digit = n % 10;
if (digit_seen[digit])
{
break;
}
digit_seen[digit] = true;
n/=10;
}

if (n>0 && digit ==8)
{
printf("Repeated 8's");
}
else
{
printf("No 8's found");
}
return 0;
}

Answer

If I understand your problem, you want to know the number of occurences a 8 is in your number. Like 88 has 2 8s. If that's the case, I don't see why you use a boolean array. First, you need a counter. Second, you need to know if digit is 8 for every digit and increment this counter if that's an 8. Here's an example :

#include <stdio.h>
#include <stdbool.h>
int main(void)
{
    int digit=0;
    long n;
    int counter = 0;

    printf("Enter number: ");
    scanf("%ld", &n);

    while (n>0)
    {
        digit = n % 10;
        if(digit == 8)
        {
            counter++;
        }

        n/=10;
    }

    if (counter > 0)
    {
        printf("Repeated 8's");
    }
    else
    {
        printf("No 8's found");
    }
    return 0;
}

In this example, counter would have the number of occurrences of 8s in your number. Just display it in the printf and it's done.

Comments