-3
public static int[] twoSum(int[] arr, int target)
{
  for ( int i = 0; i < arr.Length; i++ )
  {
    for ( int j = i + 1; j < arr.Length; j++ )
    {
      if ( ( arr[i] + arr[j] ) == target )
      {
        return new int[] { i, j };
      }
    }
  }
}

I have coded a function but it is giving me an error which say "not all code paths return a value" 2 times, i am really not understanding where the problem is, Please Help me by providing a Fix for this problem. I am having really hard time solving the error.

MobixProd
  • 11
  • 1
  • 5
    Consider what happens when at no point `( arr[i] + arr[j] ) == target`. – GSerg Jul 08 '20 at 19:01
  • Yeah I understand it now , the problem was that only when the if condition is satisfied then only it is going to return. But incase the if statement is not satisfied then there is nothing to return, and as my function needs to return something or the other in any case, that's why the error occured. Am I right ? – MobixProd Jul 09 '20 at 03:19

2 Answers2

0

You forgot to return something ouside the loop:

public static int[] twoSum(int[] arr, int target)
{
  for ( int i = 0; i < arr.Length; i++ )
    for ( int j = i + 1; j < arr.Length; j++ )
      if ( ( arr[i] + arr[j] ) == target )
        return new int[] { i, j };
  return null;
}

Indeed, in the case of the if condition is never satisfied, the method need to return a thing, null, an empty array new int[0] or what you want, because the clause return in the loop is never reached.

  • Yeah I understand it now , the problem was that only when the if condition is satisfied then only it is going to return. But incase the if statement is not satisfied then there is nothing to return, and as my function needs to return something or the other in any case, that's why the error occured. Am I right ? – MobixProd Jul 09 '20 at 03:19
  • Yes, that's it. –  Jul 09 '20 at 08:18
0

The error means that all the paths (if - else, what happens after a for/while) should return something (matching the declared return type).

In your case you need just a return at the end:

 public static int[] twoSum( int[] arr, int target)
 {

   for (int i = 0; i < arr.Length; i++) 
        {
      for (int j = i + 1; j < arr.Length; j++)
          {  
         if ((arr[i] + arr[j]) == target)
          {
            return new int[] {i , j};
          }
        }
     }
     return null;
  }
ddfra
  • 2,413
  • 14
  • 24