Jafar
Jafar

Reputation: 1

No return error in c

I'm getting an error saying no return for this function. This function is supposed to return the number of even numbers in an array.

int even (int a[],int size){
int a;
for(a=0; a< size; a++)
{
    if (abcdef[a] % 2 == 0)
    {
        printf("%d", abcdef[a]);
    }
    return 0;
}

Upvotes: 0

Views: 71

Answers (2)

l-l
l-l

Reputation: 3854

You should try something like this:

int even (int myArray[],int size){
   int count = 0;
   int a;
   for(a=0; a<size; a++)
   {
      if (myArray[a] % 2 == 0)
      {
          printf("%d", myArray[a]);
          count++;
      }
   }
   return count;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

If you want to return something, you have to

  • Calculate whatever you want to return
  • Add a return statement returning the result of your calculation.

In your code you are not doing either of these two things:

  • You have no variable that would keep count of even numbers, and
  • You are returning from the middle of your for loop.

To fix this, add an int count = 0 variable before the loop, increment it every time you print an even number, and move the return statement to the back of your code:

int count = 0;
for(...) { // Your "for" loop
    if (...) { // if the number is even...
        ...
        count++; // Increment the count
    }
}
return count; // Return goes outside the loop

Upvotes: 3

Related Questions