someone explain this code? why the output is 9 if you need c++ version of it let me know | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

someone explain this code? why the output is 9 if you need c++ version of it let me know

import java.io.*; class GFG { static int fun(int i) { if (i % 2 == 1) return (i++); else return fun(fun(i - 1)); } public static void main (String[] args) { System.out.println(" " + fun(10) + " "); } } // This code is contributed by Shubhamsingh10

12th Dec 2020, 5:12 PM
Khaled ^^ خالد القريشي‎
Khaled ^^ خالد القريشي‎ - avatar
5 Answers
+ 2
Look: initially, when we call the function, we pass it 10, and the condition "10% 2 == 1" is false. So the "else" block is triggered and we call this function, but we already pass 10 - 1 to it, that is, 9 and for 9 the condition "9% 2 == 1" is true, and the function returns "9 ++", that is, it returns 9, which is printed to the console, and then increments this 9
12th Dec 2020, 5:20 PM
Иван Чикyнов
Иван Чикyнов - avatar
+ 2
in c++, c #, c, and in all similar languages ​​there will be the same situation
12th Dec 2020, 5:24 PM
Иван Чикyнов
Иван Чикyнов - avatar
0
Khaled ^^ خالد القريشي‎ Because 9 % 2 == 1 so i++ will give 9
12th Dec 2020, 5:17 PM
A͢J
A͢J - avatar
0
I said in my question that I can provide the code in C++ as well, instead of posting two question. And it does not really matter what is the language it just needs explanation. Thank you
12th Dec 2020, 5:21 PM
Khaled ^^ خالد القريشي‎
Khaled ^^ خالد القريشي‎ - avatar
0
@Иван Чикyнов very good explanation, Thank you
12th Dec 2020, 5:23 PM
Khaled ^^ خالد القريشي‎
Khaled ^^ خالد القريشي‎ - avatar