C language simple function recursion introduction and topic application Ⅰ

simple function recursion


Two necessary conditions for recursion

  • There is a constraint, when this constraint is met, the recursion does not continue.
  • Getting closer and closer to this condition after each recursive call

Write a function that calculates the length of a string without creating a variable

This topic has been introduced in detail in the previous article Implementing strcpy and strlen functions.

find the factorial of n

For the factorial of n, when N<=1, the factorial of N is 1, and when N>2, !n=n*fac (n-1) (where fac is the factorial function)

int fac(n)
{
  if(n<=1)
  return 1;
  if(n>1)
  return n*fac(n-1);
}
  • The constraints in this function, n<=1,
  • n-1Make each recursion get closer to this condition, and let the function enter the innermost, that is, when nn<=1
    Find the nth Fibonacci number
    When n<=2, the value is 1, and when n>2, fib=(n-1)+(n-2)
int fib(n)
{
  if(n<=2
  {
  return 0
  }
  else
  return fib(n-1)+fib(n-2)
  • The constraints in this function, n<=2,
  • n-1And n-2get closer to this condition after each recursion, let the function enter the innermost, and then return layer by layer.

However, the recursive function has a lot of repetition, and the larger the incoming n is, the more heavy the calculation is. So using the loop method can greatly improve the efficiency

int fib(int n)
{
    int a = 1, b = 1;
    int c = 1;//当n小于2时直接返回1

    while (n > 2)
    {
        c = a + b;
        a = b;
        b = c;
        n--;
    }
    return c;
}

int main()
{
    int a = 0;
    printf("%u", fib(a));
    getchar();
    system("pause");
    return 0;

Here, by defining three variables, the value of c is stored in the required Fibonacci number, and then a and b are used to update the evaluation of the next Fibonacci number each time. Output in the form of %u in order to be the correct number, to avoid the most significant bit being 1 to become a negative number.
1

Write a function to implement n^k, using recursion

int func(int n, int k)
{
    if (k <= 1)//限定递归终止条件
    {
        return n;  //返回n开始逐层返回
    }
    return n*func(n, k - 1);
}
int main()
{
    int n = 5;
    int k = 4
;
    printf("%u", func(n,k));
    system("pause");
    return 0;
    //编写一个函数实现n^k,使用递归实现

}

Write a recursive function DigitSum(n) that takes a non-negative integer and returns the sum of the numbers that make it up. For example, calling DigitSum(1729) should return 1+7+2+9, whose sum is 19

int DigitSum(unsigned int n)
{
    if (n <= 9)
    {
        return n; //在n之只有一位的时候直接返回
    }
    return n % 10 + DigitSum(n / 10);//表示将每次的取模相加
}
int main()
{
    int num = 0;
    scanf("%d", &num);
    printf("%d", DigitSum(num));
    system("pause");
    return 0;
}

write picture description here
Similarly, make a slight change to the function to print every bit of the function.

void Digitprint(unsigned int n)
{
    if (n <= 9)
    {
        printf("%d ", n);
    }
    else
    {
        DigitSum(n / 10);
        printf("%d ", n % 10);
    }
}
int main()
{
    int num = 1234;
    Digitprint(num);
    system("pause");
    return 0;
}   

For those who have just come into contact with recursion, they all want to track the whole process of recursion. For simple recursive functions, etc., it is best to draw the flow chart of function calls and returns on paper, which is easy to understand and remember. Let's start with the case of termination conditions and the constraints of recursion. Here is an interesting article sharing about the Tower of Hanoi.

The point of understanding recursion is mainly to give up! Give up your attempt to understand and track the whole process of recursion, and only understand the transition between the two levels of recursion and the conditions for the termination of recursion. Imagine you are in a tropical jungle and accidentally discover the 10-story Tower of Hanoi. Just when you were thinking about how to move it, a native came out of the forest and offered to help you move the tower. His name is Ersha, and he wears a straw hat with the word 2 on it. He claims to move the first and second disks to any post. You had an idea and asked, "Don't you have a brother named Sansha?" "Yes, sir, how did you know? He will move the first to the third plate." "Then you go and call him, I don't need you anymore." So Sansha came, and he also wore a straw hat with the word 3 on it. You said, "San Sil, help me move the first three dishes to the C-pillar." San Si pondered for a while and walked into the woods, when you heard him yell: "Er Sil, come out and help me move the first two dishes." To C!" You started dozing off because of the heat. In the haze, you didn't see how Er Silly worked. After Er Silly finished, he walked into the forest and shouted, "Old 3, I'm done!" San Sil came out, moved the third disk from A to B, and then I went to call Ersha again: "Second, help me move the first two dishes back to A! "I won't say much about the rest. In short, San Sil actually only moves the third plate, and the others are called Er Sil. The last step is to move the third plate to C, and then call Er Sil to move the first two plates. After returning to C, you called Sansha and said to him, "Actually, you don't know how to move the three plates to C step by step, do you? "Three foolishly said: "Didn't I finish the task?" "You said: "But you actually asked your brother Ersha to do most of the work? "Three foolish said:" I outsourced to him and your fart? "You asked: "Did Er fool also outsource to someone?" "San smirked: "This has nothing to do with me? "You thought hard all night, and the next day, you walked into the forest and shouted, "Ten fools, where are you?" "A man with a No. 10 straw hat on his head, ten stupid, said: "Master, what's the matter with you?" "I want you to help move plates 1 to 10 to the C-pillar." "Okay, sir. "Ten Silly turned around and walked towards Lin Nei. "Wait a minute, why don't you go back and call your brother Jiu Silly?" "Master, how did you know? ""So you ordered him to move the first nine plates over and over, and you only need to move the tenth plate a few times, right? ""Yes! ""Do you know how he did it? ""This has nothing to do with my fart? "You sighed and decided to give up. The ten fools started to work. The woods were full of one after another screams: "Nine fools, come on!" " "Old eight, it's your turn! ""Five idiots! . . . ""Three fools! . . . ""Damn! "You noticed that Dasha never calls anyone, but Dasha's job is also the easiest. He just moves the first plate around. After a few years, the work is over. Ten fools come to you. You ask ten fools. : "Who taught you to work like this? "Ten foolishly said: "My father. He left me this note. "He took a small note from his pocket, which read: "Take the plate with the number of your hat to the goal post." If a plate is holding you down, ask an older brother above you to remove it. If a plate is taking up the post you're going to, ask your brother to move it out of the way. When your plate has moved to the target, ask your brother to bring the plate that should be on top of you back on top of you. "You asked inexplicably: "What if the idiot doesn't have a brother? "Ten smirked: "He only cares about the first plate, so he will never encounter those two 'ifs', and there is no plate that should be placed on the first plate. But then he suddenly changed color, as if he had leaked a huge secret. He gave you a panicked look, and fled into the woods quickly. The next day, you went to the woods to search for these ten brothers. They have disappeared. You have found a hut for one person only, but there are ten straw hats with numbers one to ten written on them. "Old eight, it's your turn!" "Five fools!..." "Three fools!..." "Dasha!" You noticed that Dasha is never called anyone, but Dasha's job is also the easiest, he Just move plate one around. After a few years, the work is over. Ten fools came to you. You ask Shisha: "Who taught you to work like this?" Shisha said, "My father. He left me this note." He took out a small note from his pocket and wrote on it "Move the plate according to the number of your hat to the target post. If a plate is holding you down, ask a brother above you to remove it. If there is a plate that occupies the post you are going to, ask your brother to move it to the target post. It's not in the way. When your plate is moved to the target, ask your brother to move the plate that should be on top of you back on top of you." You asked in a puzzled way, "What if the idiot doesn't have a brother?" Ten smirked. : "He only takes care of the first plate, so he will never encounter those two 'ifs', and there is no plate that should be placed on the first plate." But then he suddenly changed color, as if revealing a huge secret. He gave you a panicked look and ran quickly into the woods. The next day, you go into the woods to search for the ten brothers. They have disappeared. You have found a hut for one person only, but there are ten straw hats with numbers one to ten written on them. "Old eight, it's your turn!" "Five fools!..." "Three fools!..." "Dasha!" You noticed that Dasha is never called anyone, but Dasha's job is also the easiest, he Just move plate one around. After a few years, the work is over. Ten fools came to you. You ask Shisha: "Who taught you to work like this?" Shisha said, "My father. He left me this note." He took out a small note from his pocket and wrote on it "Move the plate according to the number of your hat to the target post. If a plate is holding you down, ask a brother above you to remove it. If there is a plate that occupies the post you are going to, ask your brother to move it to the target post. It's not in the way. When your plate is moved to the target, ask your brother to move the plate that should be on top of you back on top of you." You asked in a puzzled way, "What if the idiot doesn't have a brother?" Ten smirked. : "He only takes care of the first plate, so he will never encounter those two 'ifs', and there is no plate that should be placed on the first plate." But then he suddenly changed color, as if revealing a huge secret. He gave you a panicked look and ran quickly into the woods. The next day, you go into the woods to search for the ten brothers. They have disappeared. You have found a hut for one person only, but there are ten straw hats with numbers one to ten written on them. strip. "He took a small note from his pocket, which read: "Take the plate with the number of your hat to the goal post." If a plate is holding you down, ask an older brother above you to remove it. If a plate is taking up the post you're going to, ask your brother to move it out of the way. When your plate has moved to the target, ask your brother to bring the plate that should be on top of you back on top of you. "You asked inexplicably: "What if the idiot doesn't have a brother? "Ten smirked: "He only cares about the first plate, so he will never encounter those two 'ifs', and there is no plate that should be placed on the first plate. But then he suddenly changed color, as if he had leaked a huge secret. He gave you a panicked look, and fled into the woods quickly. The next day, you went to the woods to search for these ten brothers. They have disappeared. You have found a hut for one person only, but there are ten straw hats with numbers one to ten written on them. strip. "He took a small note from his pocket, which read: "Take the plate with the number of your hat to the goal post." If a plate is holding you down, ask an older brother above you to remove it. If a plate is taking up the post you're going to, ask your brother to move it out of the way. When your plate has moved to the target, ask your brother to bring the plate that should be on top of you back on top of you. "You asked inexplicably: "What if the idiot doesn't have a brother? "Ten smirked: "He only cares about the first plate, so he will never encounter those two 'ifs', and there is no plate that should be placed on the first plate. But then he suddenly changed color, as if he had leaked a huge secret. He gave you a panicked look, and fled into the woods quickly. The next day, you went to the woods to search for these ten brothers. They have disappeared. You have found a hut for one person only, but there are ten straw hats with numbers one to ten written on them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324591593&siteId=291194637