Reputation: 1498
I am wondering how to approach writing a function that would return whether there were at least three values not equal to 0. I've searched for similar problems, but I couldn't find any effective solution. In order to explain my problem, here is an example:
I have an array which contains these elements: [1,0,2,0,4,0,0,3,0,0]
. I want to check if there are at least 3 elements not equal to zero.
My code would return 1
if there are at least 3 elements != 0
, or return 0
if there are less than 3 elements !=0
.
So in my example it should return 1
.
Upvotes: 4
Views: 25395
Reputation: 1498
i'd like to share my solution
int check(){
int arr[10]= [1,0,2,0,4,0,0,3,0,0];
int total=0;
for(int i=0;i<=10;i++){
total+=arr[i];
}
return total;
}
thank you guys for trying to solve my problem <3
Upvotes: -1
Reputation: 6044
int non_zero(int a[], int lim) {
int i, count;
count = 0;
for (i = 0; i < lim && count < 3; i++)
if (a[i] != 0)
count++;
return count == 3 ? 1 : 0;
}
Upvotes: 1
Reputation: 36446
Count the number of elements not equal to zero. If less than three, return false, else return true.
In order to obtain the count, loop through the contents of the array using a for loop and then use an if statement to test if the element is zero.
Upvotes: 5