Gabbar Gabbar - 4 months ago 8
Java Question

What will be the output of these two codes?

I am new to programming and while practicing some questions I came across a code in C.

void count(int n)
{
static int d = 1;
printf("%d ", n);
printf("%d ", d);
d++;
if(n > 1) count(n-1);
printf("%d ", d);
}
int main()
{
count(3);
}

Output:
3 1 2 2 1 3 4 4 4


Can anyone explain me to that why the output is not 3 1 2 2 1 3 4 as I am expecting.
I tried writing this code in java and the output is not even close to my expectation

public static void main (String[] args)
{
count(3);
}
static void count(int n){
int d = 1;
System.out.print(n+" ");
System.out.print(d+" ");
d++;
if(n>1)count(n-1);
System.out.print(d+" ");

}

Output:
3 1 2 1 1 1 2 2 2


Is there anything I am missing about function and method calling procedure.

sps sps
Answer

In C a static variable retains its value accross function calls.

With this in context, you can see what happens when count(3) is called.

count(3)
prints: 3 1

    count(2)
    prints: 2 2   

        count(1)
        prints: 1 3 4 

    count(2)
    prints: 4   

count(3)
prints: 4

You are missing the last two 4 because you are forgetting that:

once `count(1)` returns `count(2)` prints the value of `d` once more, and
once `count(2)` returns `count(3)` prints the value of `d` once more

Now, for your java code, it is not equivalent to the C code, because d is not a static member. You can make it similar to yourC code by making d a static member.

/* ... Some code ...*/
static int d = 1;
public static void main (String[] args) 
{
    count(3);
}

static void count(int n){
// Remove this line
/*int d = 1;*/
/* ... same code ...*/
/* ... same code ...*/
}

This java code should give same result as your C code.

Comments