Logic : For counting numbers in array we are using comparison operators, but some time interviewer will ask this question check your coding knowledge. So we can count number of zeros without using comparison operator also, by using “!” operator.
Suppose my array input is like this:
5
|
0
|
6
|
9
|
0
|
4
|
0
|
1
|
0
|
6
|
If I used “!” with each array element while traversing array then values are:
0
|
1
|
0
|
0
|
1
|
0
|
1
|
0
|
1
|
0
|
Now do sum of above array values, sum is 4. So number of zero values also 4
C program :
int zeros_in_array( int a[] , int count) { int i, sum = 0 ; for (i =0 ; i < count ; i++) { sum+=!a[i]; } return sum; } int main() { int arry[] = {5, 0, 6, 9, 0, 4, 0, 1, 0, 6}; int num = 10; // Array values count printf(“Zeros in array : %d”, zeros_in_array(arry, num)); }
Count Non-Zero values in array :
Some interviewer will ask count non-zero values in array or how many non-zero values are present in array without using comparison operators?In this case we need to use “!” operator twice with each array values. Then result array after doing twice “!” operation of with each array value:
1
|
0
|
1
|
1
|
0
|
1
|
0
|
1
|
0
|
1
|
Here we know !!0 = 0 and !!1 = 1 also !!5 = 1.
Now do sum of above array values, sum is 6. So number of non-zero values also 6.
C prograom :
int non_zeros_in_array ( int a[] , int count) { int i, sum = 0 ; for (i =0 ; i < count ; i++) { sum+=!(!a[i]); } return sum; } int main() { int arry[] = {5, 0, 6, 9, 0, 4, 0, 1, 0, 6}; int num = 10; // Array values count printf(“Non-zero values in array : %d”, non_zeros_in_array(arry, num)); }
No comments:
Post a Comment