I have some question from the exam in which I need to deduce the output of the following code:
01 int foo(int a) {
02 print 'F';
03 if (a <= 1) return 1;
04 return bar(a, foo(a-1));
05 }
06
07 int bar(int x, int y) {
08 print 'B';
09 if (x > y) return baz(x, y);
10 return baz(y, x);
11 }
12
13 int baz(int x, int y) {
14 print 'Z'
15 if (y == 0) return 0;
16 return baz(x, y-1) + x;
17 }
18
19 void main() {
20 foo(3);
21 }
my question is what tactic will be the best to solve this kind of the questions? I’m not allowed to use PC of course
P.S. You can use eager evaluation as in c++ or normal order evaluation(output will be different of course, but I’m interested in tactics only), I tried to solve it using stack, every time write the function which I call, but anyway it is complicated
thanks in advance for any help
I would use a “bottom-to-top” attempt:
bazis the function that is called, but doesn’t call other functions (except itself). It outputs ‘Z’ exactlyy + 1times, the return code isx*y(you addxafter each call).baris the “next higher” function, it outputs ‘B’ once and callsbazwith its lower argument as the second parameter – the return code isx*y, too.foois the “top” function (right aftermain) and its the most complicated function. It outputs ‘F’, not only once, butatimes (because of thefoo(a-1)at the end that is evaluated before thebarcall. Thebarcall multipliesaandfoo(a-1), which will multiplya-1andfoo(a-2)and so on, untilfoo(1)is evaluated and returns 1. So the return code isa * (a-1) * ... 2 * 1, soa!.This is not a complete analysis, f.e. we don’t know in which order the characters will be output, but it is a rough scheme of what happens – and as you and other people in the comments pointed out, this is what you want – tactics instead of a complete answer.