0

hi im new to c# and was trying to code but getting error can anybody help me with this what am i doing wrong?

using System; using System.Collections.Generic; using System.Text; namespace hodder { class Program { public static void Main() { isHodder(3); } static int isHodder(int n) { int k = n; for (int i = 2; i <= n / 2;i++ ) { if ((n % 1) == 0) { return 0; } else { for (int j = 2; j <= k;j++ ) { if (n == (2^ j) - 1) { return 1; } else { return 0; } k=(2^j)-1; } } } } } } 

im getting error on " static int isHodder(int n) " 'hodder.Program.isHodder(int)': not all code paths return a value

and "Unreachable code detected " on "k=(2^j)-1"

1
  • i think its good practice to only have one return statement at the end of functions. easier to read and to debug. Commented Jul 19, 2011 at 6:45

5 Answers 5

6

The first error, "not all code paths return a value" means there is a path that the code could follow where no value would be returned (ie: calling isHodder(1)). You need to return some value outside of the for loop. Additionally, since you have an if/else block inside the second for loop the line

k=(2^j)-1; 

Will never be executed.

 static int isHodder(int n) { int k = n; for (int i = 2; i <= n / 2; i++) { if ((n % 1) == 0) { return 0; } else { for (int j = 2; j <= k; j++) { if (n == (2 ^ j) - 1) { return 1; } else { return 0; } k = (2 ^ j) - 1; } } } return 0; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Nice catch on the k=(2^j)-1;, as I think you got it before OP added the error messages. I only noticed the return...
4

This line is highly suspect:

if ((n % 1) == 0) 

Comments

1

What happens if I call isHodder(1)? Which return statement do I reach?

We may never enter the for loop at all (or if we do enter it, the compiler can't be sure that we reach a return statement before we leave the loop).

Comments

0

@jalf: is correct about the case where 2 <= n/2 (i.e., 4<=n). You will never enter the for loop in that case, so you need the return after the for.

As @Kenny suggested,

if ((n % 1) == 0) 

Is suspect. n % 1 always == n, so the condition will only be true when n == 0. However, it also looks like this might be a typo, since the condition does not test anything that varies within the loop. Did you mean

if ((n % i) == 0) 

?

1 Comment

@Lefty While I think that your edits are factually correct, IMO such a meaning affecting change should not have been an edit, but rather a comment asking the author to fix.
0

For this problem you have to use void if your function didn't return any value otherwise you have to define a return value at the end of your function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.