Home > OS >  Condtitions in void functions
Condtitions in void functions

Time:02-01

Can someone please explain to me why in the following code, after it prints out 1 consecutively , the value for a increases again? Shouldn't it stop there, after the second 1?

#include <stdio.h>
void f(int a)
{
    printf ("%d\n",a*a);
    if (a>1)
        f(a-1);
    printf ("%d ",a*a);
}
int main()
{
    f(5);
    return 0;
}

The output is

25
16
9
4
1
1 4 9 16 25

CodePudding user response:

Each recursively called function prints the passed value multiplied by itself two times

void f(int a)
{
    printf ("%d\n",a*a);
    //... 
    printf ("%d ",a*a);
}

In the last recursive call the value of a is not greater than 1. So the function outputs (I do not take into account the difference in the calls of printf relative to the new line character '\n')

25  <- first call
   16  <- second call
      9  <- third call
         4  <- forth call
            1  <- fifth call
            1  <- fifth call
         4  <- forth call
      9  <- third call
   16  <- second call
25  <- first call

CodePudding user response:

That happens because you're printing twice. Just need once. Test:

#include <stdio.h>
    void f(int a) {
        printf ("%d\n",a*a);
        if(a>1)
            f(a-1);
    } 
   int main() {   
        f(5); 
        return 0;
   }

The output is now:

25
16
9
4
1

CodePudding user response:

You are presenting a really nice example of recursion.

What is happening here is that the first print, the one at the top of the function is printing the first sets os a*a, while the final print comes from the end of the recursion, let's say, when the recursion is done is printing in its way out.

Printouts before the recursion calls.

25
16
9
4
1

1 4 9 16 25 -> line from recursion.
  •  Tags:  
  • Related