Why is recursion giving unexpected results - Page 1
Forum section: electronics / general

author: shivajikobardan
author_rank: Contributor
timestamp: September 02, 2025, 07:19:35 am
content: Code:package com.example.demo;public class Testy {public static void main(String[] args) {xMethod(5);}public static void xMethod(int n) {if (n > 0) {xMethod(n - 1);System.out.println(n + " ");}}}This is the code. I supposed that this should be printing4,3,2,1,0Because:Code:package com.example.demo;public class Testy {public static void main(String[] args) {xMethod(5);}public static void xMethod(int n) {if (n > 0) {System.out.println(n + " ");xMethod(n - 1);}}}The above code was printing 5,4,3,2,1 and my guess was correct.I thought first n=5, then print 5 then n=4Then n=4, print 4 then n=3then n=3 print 3 then n=2 and so on...On that basis I constructed logic for the first program.But it is printing 1,2,3,4,5. Which baffled me.This means I do not UNDERSTAND recursion after studying programming basics for 1000 hours(in 2 years). It is embarrassing at this point. However I am not really trying to enter programming software industry so that is fair to the industry.Please provide some pointers for me.

author: tggzzz
author_rank: Super Contributor
timestamp: September 02, 2025, 08:20:13 am
content: Do you understand how function calls use the stack? Try walking through your code on paper, keeping track of the function arguments pushed on the stack.Look at the compiler output (use zero optimisation for simplicity).Single step through your code in the debugger.

author: kite31
author_rank: Regular Contributor
timestamp: September 02, 2025, 08:21:45 am
content: As a general advice for understanding recursion, walk through the loop exactly once. If it works then, it should work on repetition.The difference is that you call xMethod() before printing rather than after. Recursion stacks the calls until it has hit its full depth, then pops the returns to undertake the next action which produces a series of println statements. At the greatest depth, n == 1, pop the next and it is 2, and so on.In the first example you print before calling.

author: shivajikobardan
author_rank: Contributor
timestamp: September 02, 2025, 08:28:47 am
content: I can naively guess that it is a call stack that is being used. And it is just popping the value from the top of the stack that was pushed earlier. But I am not exactly sure of the architecture of data structure that is being used and methodologies that are being followed at code and hardware level. As a CS enthusiast, it is my basic need to understand this. Hope to get some in-depth complete insights here.

author: brucehoult
author_rank: Super Contributor
timestamp: September 02, 2025, 09:46:32 am
content: Recursion is EXTREMELY SIMPLE to reason about. Much easier than loops!Code:public static void xMethod(int n) {if (n > 0) {xMethod(n - 1);System.out.println(n + " ");}}xMethod(5)means ...- if n > 0 (it is) THEN print the results ofxMethod(4)AND THEN print 5 and a space.Clearly it prints "iii5 ". It can't possibly do anything else than print 5 last.What is the iii? It isxMethod(4), which is "jjj4 ".What is the jjj? It isxMethod(3), which is "kkk3 ".What is the kkk? It isxMethod(2), which is "lll2 "What is the lll? It isxMethod(1), which is "1 "

author: tggzzz
author_rank: Super Contributor
timestamp: September 02, 2025, 09:52:57 am
content: Quote from: shivajikobardan on September 02, 2025, 08:28:47 amYou already know the search terms necessary to find the answers you want. Use them.People here are unlikely to want to spend their precious timepoorlyduplicating information that iswidelyavailable. (BTW, ignore hardware; this is purely software)

author: golden_labels
author_rank: Super Contributor
timestamp: September 02, 2025, 09:55:04 am
content: You may approach this by imagining how the machine implements this.(1)But this is an abstract problem and the effect of this code can be evaluated as any other mathematical expression. It’s a plain function composition.Using pseudocode:Code:n = 2IF n > 0:CALL WITH n - 1PRINT n→Code:IF 2 > 0:#######################IF 2 - 1 > 0:###########################IF 2 - 1 - 1 > 0:CALL WITH 2 - 1 - 1 - 1PRINT 2 - 1 - 1###########################PRINT 2 - 1#######################PRINT 2While posting programming questions, tell which language do you use.It doesn’t matter if readers can guess that, or if in your opinion it matters or not. Just make it clear.(1)Which in fact will be invalid, as the stack is not going to be used in the second case if even most rudimentary optimization is applied.

author: shivajikobardan
author_rank: Contributor
timestamp: September 02, 2025, 10:45:57 am
content: I researched a bit further and thus I will rewrite my question further more clearly so that people can understand where my concern is.# Title: Recursive function and call stack: Basic to Advanced understanding required!I was solving this particular problem from the textbook in the journey of self-learning.Trace and Find the output.package com.example.demo;public class Testy {public static void main(String[] args) {xMethod(5);}public static void xMethod(int n) {if (n > 0) {System.out.println(n + " ");xMethod(n - 1);}}}This was insanely easy for me to grasp. First I will print 5 then call xMethod(4).Next time, I will then print 4 then call xMethod(3)And so on.The output will be 5,4,3,2,1.The previous question was twisted by a bit. Like this:package com.example.demo;public class Testy {public static void main(String[] args) {xMethod(5);}public static void xMethod(int n) {if (n > 0) {xMethod(n - 1);System.out.println(n + " ");}}}I thought OK Fine. I will now just decrement n before printing, that is all. And got 4,3,2,1,0 as my expected hand traced output. Poor me, I was very wrong.The output is 1,2,3,4,5.Based on the solution, I can (obviously) see a stack is being used.I do not see a reason why the print function should execute in the second case.Once we call xMethod(1) then We will call xMethod(0). Now in next iteration we are at base case as n no more is greater than zero.Since nothing is specified for base case, I assume it will simply return (return what i do not know maybe that is the source of the entire confusion) back.We have started popping now the if(n>0) should no more execute. Hence, print function should no more execute. This is my concern.I hope I am clear.# Edit 2Based on further research, it seems to be that once xMethod(0) is executed, we execute print function.Let's say xMethod(0) returns to xMethod(1) Nothing. But the return should be happening all at once (without executing the print function is what I feel). So, x(1) returns nothing to x(2).......and so on till x(4) returns nothing to x(5). Finally the print function should be executed. But if that is the case, how will the n values be stored? Because stack has already been popped by now. How will the program remember the values that were already popped from stack?This leads me to believe the most possible thing. Popping and printing happens one after another instead. But why? I do not understand that. I am not seeking some deep level stuff, but simple logic and understanding is fine.

author: kite31
author_rank: Regular Contributor
timestamp: September 02, 2025, 11:03:53 am
content: It seems to me that excellent advice has been given by various other people, yet I will try one more time to help you understand the difference between calling xMethod() after or before the print.You stand at the top of a staircase with three steps. In version 1, you print your number then take a step down while reducing the number. Print comes before xMethod(). Repeat until you reach the bottom step. There is nothing left to do so you return to the stop step with no further actions in the code. The numbers are 3 2 1In version 2 you take a step down while reducing the number, then another step while reducing the number, then another to the bottom. At no time have you yet reached a print instruction, only xMethod which took you to the next step. Now you face a series of print instructions as you step back up but, being at the bottom, your first print is the 1 you are holding. Going up to the top you have 1 2 3.As mentioned, there are great resources out there. Given you are still asking here, maybe this will help.

author: golden_labels
author_rank: Super Contributor
timestamp: September 02, 2025, 09:14:04 pm
content: shivajikobardan, don’t try to do it in your mind. Use pen and paper (most convenient) or write it in some text editor.While reporting back, tell us what you did. If you just repeat, that you don’t understand, we don’t know your thinking process. And if we don’t know your thinking process, we can’t correct it.You wrote how function calls terminate. Yes, this is correct. But it doesn’t say anything about printing in relation to the calls. And this is the crucial part here.In myearlier explanationI show the final, expanded result. You just follow the second code snippet. It literally shows in what order prints are done. It’s linear code with no recursion or loops, and conditionals are left only for clarity and determine nothing.Yet another option is using the normal method with tabulating variable values. You just need to add more columns for recursive calls. And perhaps recursion depth to keep track of it.

author: sleemanj
author_rank: Super Contributor
timestamp: September 02, 2025, 10:02:25 pm
content: I think your confusion might be that you don't understand two things1. Function calls are encapsulated, what happens in them, doesn't affect what happens out of them (iognoring globals, I/O etc), even if it's a recursive call.2. When a function ends, either by explicit return, or an implicit, then it returns controil back to the point at which the function was called.Your example `xMethod(5);` withCode:public static void xMethod(int n) {if (n > 0) {xMethod(n - 1);System.out.println(n + " ");}}Performs the following stepsCode:1. Call xMethod(5); making n1 = 51. Because n1 > 0, call xMethod(n1 - 1); making n2 = 41. Because n2 > 0, call xMethod(n2 - 1); making n3 = 31. Because n3 > 0, call xMethod(n3 - 1); making n4 = 21. Because n4 > 0, call xMethod(n4 - 1); making n5 = 11. Because n5 > 0, call xMethod(n5 - 1); making n6 = 01. Because n6 == 0, return2. Print n5 + " " ("1 ") and return2. Print n4 + " " ("2 ") and return2. Print n3 + " " ("3 ") and return2. Print n2 + " " ("4 ") and return2. Print n1 + " " ("5 ") and return2. End

author: radiolistener
author_rank: Super Contributor
timestamp: September 04, 2025, 02:48:04 am
content: Quote from: shivajikobardan on September 02, 2025, 07:19:35 amThere are 3 mistakes in your code:1) You callxMethodfirst andprintlnsecond. It is important to invoke methods in the order you want them executed. In your case,xMethodis called first and it calls itself recursively. As a result, execution reaches the deepest recursive call beforeprintlnis executed. Only as the recursion unwinds does control return to the original call, causingprintlnto execute last in the first call and first in the deepest call.2) You expect the output 4, 3, 2, 1, 0, but you call xMethod from main with the value 5 instead of 4.3) In xMethod, you check if (n > 0), so only values greater than 0 are printed. Since you expect 0 to be included, the condition should be if (n >= 0).Here is the corrected code with these issues fixed:Code:public class test {public static void main(String[] args) {xMethod(4); // use 4 to start from 4}public static void xMethod(int n) {if (n >= 0) { // use n >= 0 to include value 0System.out.println(n + " "); // first call to printlnxMethod(n - 1); // second enter into recursion}}}

author: brucehoult
author_rank: Super Contributor
timestamp: September 04, 2025, 06:47:43 am
content: Quote from: radiolistener on September 04, 2025, 02:48:04 amThese are not mistakes. It is example code to be analysed and understood.Recursive calls can legitimately be the first action a function takes, the last action, or something in the middle -- possibly multiple times/places.And I believe advice to simulate it, think about stacks etc, is misguided. The point of recursion is that it permits -- encourages -- STATIC analysis of one execution of a function in isolation, assuming that other functions correctly do their job, as defined by their specification. For this, it is irrelevant whether those calls are of other functions (e.g. printf()) or recursive calls of the same function.The specification of the function in question is "Print whole numbers from 1 to n, inclusive, in that order, with each number followed by a space character.You function implements a different specification: printing numbers in descending order.

author: radiolistener
author_rank: Super Contributor
timestamp: September 04, 2025, 07:30:48 am
content: Quote from: brucehoult on September 04, 2025, 06:47:43 amAs I understand the original poster’s message, his intention was actually to implement the function so that itprints the numbers in descending order. He even wrote:Quote from: shivajikobardan on September 02, 2025, 07:19:35 amHowever, the implementation he ended up with matches the specification you mentioned - printing whole numbers from 1 to n in ascending order:Quote from: shivajikobardan on September 02, 2025, 07:19:35 amwhich is why he was confused by the result.The main mistake of the original poster is actually quite simple: he just calls println and xMethod in the wrong order. For some reason, nobody noticed this initially, and the discussion shifted to recursion details, yet the core error was never clearly explained to him.In short, the original poster intended to write code that prints4,3,2,1,0. However, his code does not behave as expected and instead outputs 5,4,3,2,1. He is unable to understand why. Above, I have outlined three mistakes in his code that cause it to behave differently from what he intended.Perhaps I misunderstood something, but that is how I read his message...

author: shivajikobardan
author_rank: Contributor
timestamp: September 04, 2025, 08:14:30 am
content: brucehoult is correct. It is purposely given like that for us to analyze and learn.

author: golden_labels
author_rank: Super Contributor
timestamp: September 04, 2025, 11:28:39 am
content: Quote from: radiolistener on September 04, 2025, 07:30:48 amNo, and it is clear: they provided a snippet that does exactly what you consider to be the question. Why would they post the correct answer and then ask, how to write it? (This is a rhetorical question, you are expected to not reply to that)Quote from: shivajikobardan on September 04, 2025, 08:14:30 amAnd what is the progress with analyzing and learning? You still didn’t give us anything, which could be used to help you.

author: magic
author_rank: Super Contributor
timestamp: September 04, 2025, 01:01:16 pm
content: Quote from: sleemanj on September 02, 2025, 10:02:25 pmBasically this. You need to understand that thenwhich equals 5 when xMethod() is initially called by main() isseparatefrom thenwhich equals 4 when xMethod() calls itself.So the meaning of xMethod() is:if (n > 0) {make a copy of n, decrement it by 1, run xMethod() recursively on the decremented copy of nafter recursive xMethod() completes execution:print the original value of n} else {do nothing and return immediately, allowing earlier xMethod() to continue}This obviously prints 1 2 3 4 5.

author: radiolistener
author_rank: Super Contributor
timestamp: September 04, 2025, 03:30:29 pm
content: Quote from: golden_labels on September 04, 2025, 11:28:39 amHowever, the original poster did not mention any of that in original post. In his first message, he clearly stated that he wrote the initial code expecting it to produce 4,3,2,1,0, but it actually outputs 1,2,3,4,5, and he couldn’t understand why. That is all I saw, so I didn’t try to speculate about what task he was given or what his teachers intended. I simply explained why the code he wrote produces a different result from what he expected and how to fix it to get 4,3,2,1,0, as he intended. He didn’t ask about anything else in his first message.

author: TheCalligrapher
author_rank: Regular Contributor
timestamp: September 04, 2025, 03:51:16 pm
content: Quote from: shivajikobardan on September 02, 2025, 07:19:35 amUm... Your question sounds like "why 2+2 is 4 when I expected it to be 11?" Questions like that are impossible to answer without additional clarifications, since in the original form they simply make no sense.First and foremost, you have to explain to us why you expected this code to output "4,3,2,1,0"? Why, really? And what puzzles me most is why you expected this sequence to start with 4, when the top-level call in your code is clearly given 5 as an argument. Also, why did you expect to see 0 in the output when the `if` in your code is clearly crafted to prevent this from happening?

author: kite31
author_rank: Regular Contributor
timestamp: September 04, 2025, 10:11:33 pm
content: Quote from: TheCalligrapher on September 04, 2025, 03:51:16 pmStraightforwardly, shivajikobardan expected the println which is subsequent to the recursive call to be executed at once despite the method call prior. Thus, 4,3,2,1,0 makes sense as an output, provided only that 2+2 = 11After all of these contributions, I should hope he or she has grasped that by now. Some feedback would be nice.

author: ledtester
author_rank: Super Contributor
timestamp: September 04, 2025, 10:15:29 pm
content: Quote from: TheCalligrapher on September 04, 2025, 03:51:16 pmI think this would have been a good way to direct the conversation - the crux of the problem might have gotten to much more quickly.

author: brucehoult
author_rank: Super Contributor
timestamp: September 05, 2025, 03:52:26 am
content: Quote from: radiolistener on September 04, 2025, 07:30:48 amWhat do you mean "no one noticed". Everyone noticed, including OP. The original message included two versions copies of the code with both orders. OP, and everyone else, completely understood that there were two orders of those two statements. OP was simply confused about why the two orders produced different results.

author: IanB
author_rank: Super Contributor
timestamp: September 05, 2025, 05:21:25 am
content: The OP was (and probably still is) simply confused. There is no need for any qualification.I mean, just consider a fundamental thing:Code:if (n > 0) {xMethod(n - 1);System.out.println(n + " ");}Quote from: shivajikobardan on September 02, 2025, 07:19:35 amGiven the test for n > 0, there is no way for the code ever to print a value of "0".

author: kite31
author_rank: Regular Contributor
timestamp: September 05, 2025, 05:59:45 am
content: Quote from: IanB on September 05, 2025, 05:21:25 amThere is if the OP imagines that theprintlnstatement is  executed within the same sequence as thexMethodcall, without xMethod being called first.That in fact appears to have been their fundamental error. Walk through the code as ifxMethoddid not divert execution from the subsequentprintlnuntilafterprintlnexecuted.I know it makes no sense to us, but the OP thought execution would be:Code:decrement n(defer call to xMethod)print nnow execute the xMethod callas if the entirety of the method executed and only then did the earlier recursive call actually happen.Edit: attempt to clarify

author: shivajikobardan
author_rank: Contributor
timestamp: September 05, 2025, 06:04:18 am
content: Thank you all I seem to have get it.

author: IanB
author_rank: Super Contributor
timestamp: September 05, 2025, 02:15:00 pm
content: Quote from: kite31 on September 05, 2025, 05:59:45 amBut no. The println(n) statement is inside the if (n > 0) block. Therefore it can never be executed when n = 0, regardless of whether xMethod is called before or after.

author: kite31
author_rank: Regular Contributor
timestamp: September 05, 2025, 10:39:02 pm
content: Quote from: IanB on September 05, 2025, 02:15:00 pmObviously I know that.I was trying to explain what the OP initially imagined might somehow be the case. We know 2+2 != 11

author: golden_labels
author_rank: Super Contributor
timestamp: September 06, 2025, 01:28:13 am
content: But, but… 2 + 2 = 11 (modulo 7)!

author: kite31
author_rank: Regular Contributor
timestamp: September 06, 2025, 02:44:54 am
content: Quote from: golden_labels on September 06, 2025, 01:28:13 amor base 3

author: radiolistener
author_rank: Super Contributor
timestamp: September 06, 2025, 04:56:48 am
content: Quote from: kite31 on September 06, 2025, 02:44:54 amIndeed, since we are discussing programming, it seems only fair to appeal to one of the great guides of our discipline - Donald Ervin Knuth, the author of The Art of Computer Programming. Back in 1960, Knuth proposeda complex-base systemwhose radix is an imaginary or complex number.If we take such a base \$xj\$, the seemingly absurd expression\$2 + 2 = 11\$can be written in positional notation as\$2 \cdot (xj)^{0} + 2 \cdot (xj)^{0} \;=\; 1 \cdot (xj)^{1} + 1 \cdot (xj)^{0}\$Solving this equation yields the complex solution \$x = −3j\$Substituting back, the base becomes \$x \cdot j = -3 \cdot j^{2} = 3\$So, after detouring through Knuth’s imaginary number system, we come full circle: the notorious identity 2+2=11 turns out to be perfectly valid - in base 3.After all, in mathematics as in programming, changing the base is often the quickest way to make impossible things compile. And our brief detour into complex numbers just shows - when 2 + 2 looks impossible, just add a little imaginary help...

author: magic
author_rank: Super Contributor
timestamp: September 06, 2025, 07:23:09 am
content: It's kindergarten maths to show that this can (only) work in base 3:2 + 2 = 1·x + 1It would take three digits to make things complex:2 + 2 = 1292 + 2 = x² + 2x + 9-4 = (x + 1)²2i = ±(x + 1)x = -1 ± 2i

author: TheCalligrapher
author_rank: Regular Contributor
timestamp: September 12, 2025, 04:50:35 pm
content: Quote from: radiolistener on September 06, 2025, 04:56:48 amIt is indeed. However, the problem often is that some people take this as a demonstration of "two plus two equals four" not always being valid. They mistakenly believe that the above somehow demonstrates that "two plus two can be eleven". Such people fail to grasp the difference betweennotational systemsfor numbers andnumbers themselves. They fail to understand that "11" in base 3 is actuallyfour, not eleven. So, the whole "2+2=11" in base 3 just reiterates the good old "two plus two equals four".

author: radiolistener
author_rank: Super Contributor
timestamp: September 13, 2025, 07:05:07 am
content: Quote from: TheCalligrapher on September 12, 2025, 04:50:35 pmThere is no mistake at all. In base-3, 2 + 2 = 11 is absolutely valid — it only looks odd if you insist on reading it with base-10 goggles.A number is a single abstract entity, the digits we use in a given base are just a language to express that entity. You can represent the same thing with different digit sequences in different numeral systems, just like you can express the same thing meaning with different words in different languages. All of them are valid — they’re simply express exactly the same thing using different languages.Quote from: TheCalligrapher on September 12, 2025, 04:50:35 pmI understand what you wanted to say, but your phrase "11 in base 3 is actually four, not eleven" sounds a bit off, because in base 3 there is no such thing as "4". Numbers there stop at 2 — poor 3 and 4 never get invited to the party!What you probably mean to say is that "11" in base-3 represents the same quantity that we normally write as “4” in base-10. Without that clarification, some readers may get confused.Quote from: TheCalligrapher on September 12, 2025, 04:50:35 pmExactly — the equation is still true, just wearing a different base-system outfit. Same truth, different costume

author: magic
author_rank: Super Contributor
timestamp: September 13, 2025, 07:15:39 am
content: Quote from: TheCalligrapher on September 12, 2025, 04:50:35 pm

author: wilfred
author_rank: Super Contributor
timestamp: September 13, 2025, 07:17:59 am
content: Quote from: radiolistener on September 13, 2025, 07:05:07 am113is 1 x 31+ 1 x 30or 3 + 1 which equals 4. Just because there is no digit 4 used to write down the numbers in base 3 doesn't mean you can't count to 4 or represent the number 4.

author: radiolistener
author_rank: Super Contributor
timestamp: September 13, 2025, 08:05:12 am
content: Quote from: wilfred on September 13, 2025, 07:17:59 amI understand your point, but if your expression is written in base-3, there is no digit “4” in that system, so using it directly would be invalid.What you probably meant is that “11” in base-3 corresponds to 4 in base-10. If you want to express it this way, you need toexplicitlyspecify that the 4 is written in a different base than the one used by default in the expression. Otherwise, it can easily lead to confusion.In other words, writing "11 equals 4" is incorrect - this is mistake, whereas writing "113equals 410" is correct and perfectly valid.When working with an expression in base-N, it is generally expected that all numbers are interpreted in base-N by default. You cannot introduce digits or numbers from another base without explicitly indicating their base.It’s similar to writing a text in English: you cannot just drop random words in Chinese without explanation — readers won’t understand them. In the same way, if an equation is written in base-3, you cannot suddenly use a digit like “4” without explicitly specifying its base.While this may seem obvious to some, and those who understand your intent might infer it even if you ignore the rule, it is nonetheless a serious mistake to mix digits from different numeral systems in a single text or equation without explicitly specifying their bases.You may choose any numeral system as the default without explicitly specifying its base, as long as all numbers in your text or equation are consistently expressed in that system — for example, using base-3 throughout is perfectly fine. However, you cannot mix numbers from different numeral systems without explicitly indicating their bases.

author: Nominal Animal
author_rank: Super Contributor
timestamp: September 13, 2025, 10:27:53 am
content: Quote from: shivajikobardan on September 05, 2025, 06:04:18 amIf you want to explore more complex recursion systems, for example what calls are made and in what order when calculating a specific value in the Fibonacci series, I would recommend you add another tool to your arsenal:Graphviz. It is a set of programs that take textual descriptions of graphs and nets in the human-readableDOTlanguage, and draws the graph/net as an image, automatically placing nodes and edges according to tool-specific rules.dotdraws standard directed and undirected graphs and nets,circoplaces nodes in a circle, and so on.Each node does require an unique identifier, which can be text, number, or even a pointer (using format\"%p\"). I recommend using a variable and a getter function to obtain a new unique id:Code:static int unique_ids = 0;static inline int unique_id(void) {return ++unique_id;}which simply increments theunique_idsvariable and returns the incremented value.A program that calculates say the 6th number in the Fibonacci series printing the call graph would beCode:#include <stdlib.h>#include <stdio.h>static int unique_ids = 0;static inline int unique_id(void) {return ++unique_ids;}int fibonacci(FILE *dot, int n, int caller_id) {/* Grab a new unique ID, identifying this particular call in the DOT graph */int id = unique_id();/* 'result' will eventually specify the calculated n'th Fibonacci number, F(n). */int result;/* F(n) = F(n-1) + F(n-2), but F(0) = 0, F(1) = 1. */if (n < 2) {result = n;} else {result = fibonacci(dot, n-1, id) + fibonacci(dot, n-2, id);}/* Describe this node in DOT, if 'dot' is non-NULL */if (dot) {/* First, describe this node */fprintf(dot, " \"%d\" [ label=\"F(%d) = %d\" ];\n", id, n, result);/* Then describe the edge to the parent (who called this function) */fprintf(dot, " \"%d\" -> \"%d\";\n", id, caller_id);}/* As usual, this function returns the calculated n'th Fibonacci number. */return result;}int main(void) {/* Standard output consists of a directed graph in DOT language: */fprintf(stdout, "digraph {\n");/* Zero ID is the following fibonacci(stdout, 6, 0); call */int result = fibonacci(stdout, 6, 0);fprintf(stdout, " \"0\" [ label=\"fibonacci(stdout, 6, 0) = %d\" ];\n", result);/* End of directed graph. */fprintf(stdout, "}\n");/* We also print the result to standard error. */fprintf(stderr, "fibonacci(6) = %d, used %d recursive calls\n", result, unique_ids);return EXIT_SUCCESS;}To standard error, this outputsfibonacci(6) = 8, used 25 recursive callsand to standard output, the following DOT language directed graph:Code:digraph {"6" [ label="F(1) = 1" ];"6" -> "5";"7" [ label="F(0) = 0" ];"7" -> "5";"5" [ label="F(2) = 1" ];"5" -> "4";"8" [ label="F(1) = 1" ];"8" -> "4";"4" [ label="F(3) = 2" ];"4" -> "3";"10" [ label="F(1) = 1" ];"10" -> "9";"11" [ label="F(0) = 0" ];"11" -> "9";"9" [ label="F(2) = 1" ];"9" -> "3";"3" [ label="F(4) = 3" ];"3" -> "2";"14" [ label="F(1) = 1" ];"14" -> "13";"15" [ label="F(0) = 0" ];"15" -> "13";"13" [ label="F(2) = 1" ];"13" -> "12";"16" [ label="F(1) = 1" ];"16" -> "12";"12" [ label="F(3) = 2" ];"12" -> "2";"2" [ label="F(5) = 5" ];"2" -> "1";"20" [ label="F(1) = 1" ];"20" -> "19";"21" [ label="F(0) = 0" ];"21" -> "19";"19" [ label="F(2) = 1" ];"19" -> "18";"22" [ label="F(1) = 1" ];"22" -> "18";"18" [ label="F(3) = 2" ];"18" -> "17";"24" [ label="F(1) = 1" ];"24" -> "23";"25" [ label="F(0) = 0" ];"25" -> "23";"23" [ label="F(2) = 1" ];"23" -> "17";"17" [ label="F(4) = 3" ];"17" -> "1";"1" [ label="F(6) = 8" ];"1" -> "0";"0" [ label="fibonacci(stdout, 6, 0) = 8" ];}If you pipe the output todot, or save it to a file and rundotspecifying the name of that file, you will see the graph itself,(Click to embiggen)I personally have over three decades of paid software development in various programming languages, including a lot of C. Yet, I still prefer to use tools like Graphviz to verify my understanding of algorithms and even complex data structures (and how they refer to each other). Thus, I would suggest that learning how to augment your learning programs with DOT language output can help you produce better code, because you then understand the code better (as in how it works, how it computes the results, how many calls are needed, and how to make it much more efficient). For example, the above call graph shows that many Fibonacci numbers are calculated again and again, socaching the already calculated resultswould make it much faster. In reality, there are better mathematical forms to use than the basic sum formula (Binet's formula being most powerful, but requiring arbitrary-precision numbers for largern), but I'm sure you see the usefulness of such graphs.(I personally only use Linux for development. Development on Macs is very similar, but on Windows, there are quirks and exceptions, even when using WSL2. Because I do not know what operating system you use (or anyone else reading this post uses), I omitted the exact commands you use, because Graphviz is available for free and works in all operating systems. Whenever there is a graphical desktop available, it can display the graph directly, but it can also just generate the image file instead. Thus, this development pattern will work on any operating system, and even with any programming language. I've found it extremely powerful, and hope you find it useful too.)An even more important thing, in my opinion, is writing useful comments. The comments should never describe what the code does, because we can read that from the code itself. The comments should always try to convey your intent and reasoning instead, so that those reading the code can compare what the comment says about the intent for the code and what the code actually does. I did not learn this early enough, andstillhave trouble writing the kind of comments I would like to, so the earlier you learn to do this, andalways write such comments, the better a programmer you will become. I am literally limited by this, because the maintainability of the code I write suffers due to my comments not being as useful and to the point they could be! I hope you become better than I am, eventually.

author: IanB
author_rank: Super Contributor
timestamp: September 14, 2025, 02:22:43 am
content: Quote from: radiolistener on September 13, 2025, 07:05:07 amDon't be silly. Of course the number four exists when you are counting in base 3 or in any base. You can visualize it: start with the number one, and then find its successor three times. The third successor of one is the quantity four. Just as "IV" is also the quantity four.(Note that TheCalligrapher didn't write the digit "4", theysaidthe number "four". There is a difference.)This is just the same as "a dozen", or "a score" or "a gross" exist independently of notational systems. If I am counting in base 10 and you are counting in base 2, and I ask you for a gross of pencils, I will (hopefully) get the right number of pencils. Named quantities exist, regardless of the notational system in use to write them down.

author: radiolistener
author_rank: Super Contributor
timestamp: September 14, 2025, 09:54:14 am
content: Quote from: IanB on September 14, 2025, 02:22:43 amSorry for being pedantic, but the number “four” does not exist if you are counting in base‑3. I understand that you meant “four in base‑10”, but the way it was written initially is mistaken. In base‑3, there is no concept of “four” or the digit “4”.Quote from: IanB on September 14, 2025, 02:22:43 amI understand the distinction you are making between abstract numbers and their representation. However, the problem here is one of consistency in notation.When specifying the value of an abstract number, you must use a particular numeral system. Since base‑3 is the default in the context, you cannot use “four” without indicating its base, because by default only numerals valid in base‑3 may be used. However, if you explicitly indicate that “four” is in base‑10, then the statement becomes correct.In the context where base‑3 is the default, “11” is the valid numeral. Writing “11 = 4” is misleading because it mixes numeral systems without explicitly specifying the base. The correct way to express the equivalence is 113= 410, which clearly separates the abstract quantity from the symbols used to represent it.The core mistake in TheCalligrapher’s statement is assuming that base‑10 digits can be inserted into a base‑3 context without clarification. Since base‑3 contains no digit “4” using it in that context is invalid — even abstractly — unless the base is explicitly indicated.I made corrections for the TheCalligrapher quote: "eleven in base 3 is actually four in base 10, not eleven in base 10". With these corrections it will be correct. But this is not what TheCalligrapher wrote originally. And this is what I'm talking about.This is analogous to reporting measurements in meters and inches without specifying units. Or it is similar to comparing values in dBW and dBV while labeling both simply as dB. Using a consistent default is fine, but mixing units (or bases, or reference level) without clarification is misleading.In short: once a default base is established, all numerals must be interpreted within that base, or any deviation must be explicitly marked. Treating “4” as if it were valid in a base‑3 expression is simply incorrect. Even if you mean that "4" is in base‑10, if it is not explicitly marked, it is still incorrect in base-3 context.PS: The original humor in the statement that 2 + 2 = 11 is valid in base‑3 relies on the fact that the expression was written using a default numeral system, while the default system itself was not explicitly specified, leaving the choice of an appropriate default base to the reader. Using base‑3 as the default — just as one could use base‑10 or any other base — is perfectly acceptable. However, mixing values from different numeral systems without explicitly indicating their bases is incorrect.Often, the intended meaning can be inferred from context, for example, when someone writes “mHz”, it is frequently understood that he mean “MHz”. Similarly, in this case, the intended reference to “4” within a base‑3 context is generally understandable. Nevertheless, it remains an error that should be avoided, as it can create confusion, and such mistakes are not always easily resolved from context alone.Sorry for being so pedantic, but the statement about “4” in a base‑3 context caught my eye, which is why I commented it. I did not expect it to provoke such a strong reaction, as I thought these issues should be fairly straightforward and not confusing.

author: IanB
author_rank: Super Contributor
timestamp: September 14, 2025, 07:52:42 pm
content: Quote from: radiolistener on September 14, 2025, 09:54:14 amNo, I did not mean "four in base-10", I meant "four" as in the word found in the dictionary--meaning the number that comes after the number that comes after the number that comes after one. There are four fingers on your hand, and that is true whether you choose to write that number down in base 2, in base 16, or in French. It is always the same number of fingers.QuoteWhy? Can you provide a justification for that? How did people count before there were Arabic numerals or complex notation systems? How did people count when they used tally marks? Four is four is four. It is a quantity everyone knows and can relate to. It can be expressed in different number systems, but the word four is universal in its meaning. It is what you get to when you count with the natural numbers: one, two, three, four.QuoteThat may be so, but nobody is writing that, so you are constructing a straw-man argument.QuoteBut TheCalligrapher did not do that, so once again you are creating a straw man argument.QuoteOnce again, there was no "4" in a base 3 context. You are inventing it.Please stop responding to what you think you might have read, and instead try responding to what is actually written. You will do much better then.

author: radiolistener
author_rank: Super Contributor
timestamp: September 15, 2025, 02:50:42 pm
content: Quote from: IanB on September 14, 2025, 07:52:42 pmI understand your point, but whether you intend it or not, the symbol “4”is not the abstract quantity itselfbut rather itsrepresentationin the numeral system with base-10. The quantity — the concept, such as the number of fingers on a hand, is indeed independent of language or numeral system. However, not all culture expressing it using base-10 and once you write it down as "4", you are already expressing it in base-10 notation.I understand your point that when people say “four”, they intuitively think of a certain quantity. However, the mistake is to conflate that intuitive notion with the numeral system used to represent it. The word “four” or the digit “4” specifically expresses that quantity in base‑10 notation. It is not the abstract quantity itself. Please don't confuse it.Quote from: IanB on September 14, 2025, 07:52:42 pmYou are correct that the abstract quantity itself exists independently of any numeral system or language. However, the symbols "4" or “four” are not the abstract quantity, they are a representation of that quantity in base‑10. In other languages, or using other numeral systems, the same abstract quantity would be expressed differently — for example, in Chinese, the same quantity is written as "四" in base‑10.But when working within a numeral system with a fixed base, consistency is required. You can really omit explicitly stating the base if a default is established — for example, base‑10 is commonly assumed. However, if an expression is written in a context where base‑3 is the default, you cannot introduce a numeral from another system without explicitly specifying its base. Mixing values from different numeral systems without such clarification is misleading and incorrect.For example, with default base-10:- stating "11 = 4"is incorrect- stating "113= 4"is correct- stating "11 = 410"is incorrect- stating "113= 410"is correctBut with default base-3, it's a little bit different:- stating "11 = 4"is incorrect- stating "113= 4"is incorrect(this is the case we're talking about)- stating "11 = 410"is correct- stating "113= 410"is correctQuote from: IanB on September 14, 2025, 07:52:42 pmI understand your point, but from your statements it seems you are treating TheCalligrapher’s comment as if it were in a base‑10 context. However, the original expression 2 + 2 = 11 was clearly in a base‑3 context, and TheCalligrapher did not explicitly switch the base to 10. Therefore, this is not a straw man argument —it’s a typical mistake of introducing values from one context to another without explicit clarification. It’s like discussing lengths in meters and suddenly quoting a number in inches without stating the unit — that would be clearly incorrect.Quote from: IanB on September 14, 2025, 07:52:42 pmI am not responding to "what I think you might have read”. The context under discussion is the expression 2 + 2 = 11, written in using default base‑3 and explicitly defined that it written with default base-3.In that context, using the numeral “4” without specifying its base is a genuine error.It may appear obvious from context that he intended it to represent a number from a different numeral system, but the fact remains: introducing a value from another base without explicit notation is incorrect. This is not a matter of interpretation or imagination—it is a concrete issue of mixing numeral systems without clarification.For me, it is entirely obvious, that the base‑10 is not the absolute standard. I find it strange to read arguments suggesting that, because humans have ten fingers, everyone should automatically interpret any numerals with no explicit base in base‑10 only. This is simply not correct. When responding to an expression written with base‑3 as the default, one must either adhere to that base-3 notation or explicitly switch the context by indicating that the numerals in his answer are being expressed in a different base by default.It appears that some people really have difficulty distinguishing between a numeral written in base‑10 and the abstract quantity it represents, often conflating the two and assuming that a base‑10 representation is absolute. I find its hard to understand why so simple thing is still not understand, but I have at least made an effort to explain it.Sorry for being so pedantic. I understand that many people do not notice differences in context and may mix numbers across different units, numeral systems, reference points, or, for example, write “mHz” instead of “MHz” without seeing any issue. For some, pointing out such the mistake makes little difference, as they simply do not perceive it as a problem. However, I consider this to be a significant mistake.

author: radiolistener
author_rank: Super Contributor
timestamp: September 15, 2025, 05:43:57 pm
content: As I mentioned earlier, if TheCalligrapher had initially properly specified the base for the numerals 4 and 11, there would have been no reason for this discussion at all. In fact, the substance of his message essentially boils down to stating the obvious thing — like saying “cotton is fluffy” or “sugar is sweet”, since it should already be clear to everyone that 410and 1110are different numbers, while 410and 113represent the same number.And isn’t it striking how simple and transparent everything becomes once the bases are properly indicated? It immediately clarifies that “4” does not belong to the base-3 context in which it was inserted, and removes any confusion about why he claimed that 11 is 4 but not 11.However, I was somewhat surprised by the discussion, as it revealed that some people genuinely believe a number is always expressed in base-10. This is a rather puzzling misconception. In fact, the term number refers to the underlying abstract entity — the quantity, and applies equally regardless of the numeral system used to represent it.There is nothing wrong to say something like hexadecimal number, decimal number, binary number, etc.