A quick way to test whether all array elements are zero

4

TL;DR I would like to know how to clean up the first if statement. I tried looking online and found nothing.

I am writing a program to test whether a number typed by the user has repeated digits. I have managed to create a 10-element boolean array (a[10]) such that if a[i] equals 0, this means that the digit 'i' is present in the typed number at most once. If a[i] equals 1, then the digit 'i' is present in the typed number at least twice (thus is repeated). Note 0<=i<=9.

Now I am trying to analyse the values in this array such that if all values equal zero then we type "Repeated digit". And if not we say which numbers are repeated.

if(a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0 && a[4] == 0 && a[5] == 0 && a[6] == 0 && a[7] == 0 && a[8] == 0 && a[9] == 0)  
       printf("No repeated digits");
  
else  
  printf("Repeated digits: "); 
  for(i = 0; i < 10; i++) {
        if(a[i] == 1)
        printf("%d ", i); 
    }   


I can't find a way of using a for loop combined with an if loop to clean up the first if statement. I have tried looking online but can't find a solution.

Share
Improve this question
6
  • 2
    "quick" as in runtime? Or least code? – Eugene Sh. Apr 12 at 14:40
  • quick as in not having to explicitly type out that each array element equals zero. Trying to equivalently write out the first if statement using some looping mechanism. Imagine if this problem were in base 99 instead of base 10! (! for effect, not factorial) – Guthrie Apr 12 at 14:42
  • 1
    If you stored the "array" as a bit-vector in a single unsigned integer, you could check that all bits are zero with a single test: a == 0. – Ian Abbott Apr 12 at 14:57
  • As you create the array in the first place, set a flag if any element is not zero. – Eric Postpischil Apr 12 at 15:01
  • I need to check out this flag thing, first I've heard of it, sounds useful. – Guthrie Apr 12 at 15:02

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue