Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A quick way to test whether all array elements are zero

Tags:

c

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.

like image 875
Guthrie Avatar asked Dec 08 '22 09:12

Guthrie


1 Answers

There is a trick to check if an array has all elements equal to N:

if (a[0]==N && memcmp(a, a+1, (array_length-1)*sizeof(a[0]) ) == 0)
    printf("All equal to N\n");

In you case you can do:

if (a[0]==0 && memcmp(a, a+1, 9*sizeof(a[0]) ) == 0)
    printf("All zeros\n");

This code is explicitly checking the first element to be zero, and then the memcmp is doing the following checks for you:

a[0] == a[1] && a[1] == a[2] &&....

This requires no extra allocated and initialized zero array as the other memcmp -based answers do.

like image 161
Eugene Sh. Avatar answered Jan 05 '23 00:01

Eugene Sh.