user3190555
user3190555

Reputation:

Check if values in the array are even and if true return true

This is what I've done so far but the result is always 1 no matter if the array has odd or even numbers inside. What am I doing wroing?

#include <stdio.h>
#include <stdbool.h>

int main(){
    int vector[10]={2,4,6,8,10,12,14,16,18,20};
    bool function(int i){
        for(i=0,i<10,i++){
            if(vector[i]%2==0){
                return true;
                }
            return false;
            }
        }
    }
}

Upvotes: 0

Views: 198

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311196

If to follow the C Standard then you may not define a function inside another function.

Nevertheless the main problem with your function (apart from syntax errors as for example the invalid for statement) is using the return statement for the first element of the array independently on whether it is odd or even.

The program can look the following way

#include <stdio.h>
#include <stdbool.h>

bool is_even( const int a[], size_t n )
{
    size_t i = 0;

    while ( i < n && a[i] % 2 == 0 ) i++;

    return i == n;
}

#define N 10

int main( void )
{
    int vector[N] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

    printf( "All elements are even: %d\n", is_even( vector, N ) );
}

Take into account that according to the C Standard function main without parameters shall be declared like

int main( void )

Upvotes: 4

Rahul
Rahul

Reputation: 2100

Because you are returning it on a final iteration. You should return false when you have checked the whole array, not in middle.

Also, your function was never get called and so you can update it using C semantic.

#include <stdio.h>
#include <stdbool.h>

bool check_even(int vector[], int size){
    int i;
    for(int i=0; i<size; i++){
        if(vector[i] % 2==0) { 
           return true;
        }
        // return false; shift this to out of for block
     }
  return false;
}


int main(){
    int vector[10]={2,4,6,8,10,12,14,16,18,20};

    bool is_even = check_even(vector, 10); // here function will get called

    return 0 // always return with main
}

Upvotes: 1

Michael Dorgan
Michael Dorgan

Reputation: 12515

For loop should use ; between entries, not ,. You are never looping.

for(i=0;i<10;i++) 

...

Honestly, I would expect your compiler to throw at least a warning on this statement as it is missing elements of a basic for loop.

Next, you need to move your

return false;

outside the for loop or it will never iterate past the first entry.

Last, defining function within main is a not standard in C. Make it it's own function and things will be happier.

Upvotes: 1

Related Questions