Why does my code below throws an error? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does my code below throws an error?

static int Max(int x,int y) { if(x>y) { return x;} else if(x<y) {return y;} else { Console.WriteLine("x is equal to y");} } static void Main (string[]args) { Max(2, 4); } //output = error , Program.Max(int, int): not all code paths return a value Why???

17th Aug 2019, 10:58 AM
DataStream Cowboy
DataStream Cowboy - avatar
6 Answers
+ 4
If x equals y, you only print a message, but don't return a value, while the function expects you to return an integer value. If the return type of your function is not void, it must return a value, which might not be the case here, therefore an error is raised.
17th Aug 2019, 11:05 AM
Shadow
Shadow - avatar
+ 4
Just add return in your else statement, like this: ... else{ Console.WriteLine("x is equal to y"); return x; } ...
17th Aug 2019, 11:25 AM
voja
voja - avatar
+ 2
If you say static INT Max, that means function MUST return integer. Else clause doesn't return anything, you simply write to console, you must return some number just like in if and else if
17th Aug 2019, 11:21 AM
Elva
Elva - avatar
+ 2
When you return value it's not printed, you must print it manually, like Console.writeLine(Max(2,3))... For else clause you can return anything of your own choice, but remember not to use = but == if you want to test equality
17th Aug 2019, 11:31 AM
Elva
Elva - avatar
0
Shadow didnt get you still...can you point out directly where the error is or simply write the correct code Thanks
17th Aug 2019, 11:13 AM
DataStream Cowboy
DataStream Cowboy - avatar
0
Elva got it now... I should put //return x=y; not the Console.Write....... But am stuck a little bit ...because i used if statement when the first if is not true it gives no output to my code while there is more conditional down like else if and else HOW TO SOLVE THIS PROBLEM...OR SIMPLY HOW TO GIVE THE MAXIMUM NUMBER IN MY CODE ABOVE
17th Aug 2019, 11:28 AM
DataStream Cowboy
DataStream Cowboy - avatar