5

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And if one is in optimising mood, break out of the counting loop when the count reaches 3.
Pre-mature optimization on SO? Heresy!
1
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;
}

Comments

-1

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

1 Comment

This only gets the sum, not the number of nonzero elements. Also, depending on how big the array is and how big the elements of the array can be, you may end up with an overflow that puts the total back to 0, meaning it may not tell you whether any element is nonzero either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.