简体   繁体   中英

how to work function in c language anyone can explain please

In this code why n prints n times anyone have can explain please why prints call n times

 int count(int n){
        print("%d" , n);
             if(n>1){
                  count(n-1);
              }
        print("Integer value is %d\n" , n);
     return n;
    }
   int main(){
     count(3);
  }

In the code given, function is recursive. Count(n-1) calls the function again and again until the condition if(n>1) fails. So if you are passing 5 to the count function. It prints 5 times.

For count(n) your code will print something like this:

n,n-1,n-2....1 Integer value is 1
Integer value is 2
Integer value is 3
....
....
Integer value is n

Now let's look at the reason, find the recursive call for count(3) for illustration:

count(3)--print(3)
(3>1) is true---count(2)--print(2)
(2>1) is true---count(1)--print(1)
(1>1) is false exec prev func call
print(Integer value is 2) return 2
print(Integer value is 3)
return 3
In the recursion tree see where the code is printing the values.

Input: count(3)
Output:
321Integer value is 1
Integer value is 2
Integer value is 3

It prints out 6 times. This is, because the program is told so. Let's insert the function call into the main code:

int count(3) // call with 3
{
  print("%d" , 3);                      // prints 3
  if(3>1)
  {
    count(3-1);
  }
  print("Integer value is %d\n" , n);   // prints 3
  return n;
}

Again, insert the call:

int count(3) // call with 3
{
  print("%d" , 3);                          // prints 3
  if(3>1)
  {
    // count(3-1)
    {
      print("%d" , 2);                      // prints 2
      if(2>1)
      {
        count(2-1);
      }
      print("Integer value is %d\n" , 2);   // prints 2
      return 2;
    }
  }
  print("Integer value is %d\n" , 3);       // prints 3
  return 3;
}

Again:

int count(3) // call with 3
{
  print("%d" , 3);                          // prints 3
  if(3>1)
  {
    // count(3-1)
    {
      print("%d" , 2);                      // prints 2
      if(2>1)
      {
        // count(2-1);
        {
          print("%d" , 1);                      // prints 1
          if(1>1)                            // is false, no recursion any more
          {
            // count(1-1);
          }
          print("Integer value is %d\n" , 1);   // prints 1
          return 1;
        }
      }
      print("Integer value is %d\n" , 2);   // prints 2
      return 2;
    }
  }
  print("Integer value is %d\n" , 3);       // prints 3
  return 3;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM