Recursive learning of iterations and functions

Initial understanding of modular programs

In a real program, the custom function is called for nothing, and the corresponding header file is also included, as well as the function definition interface. So a simple addition function was created.
Function declaration

#ifndef __ADD_H__
#define __ADD_H__

//函数的声明
int Add(int x, int y);

#endif

I put this statement under the file whose directory is add.h, where

#ifndef __ADD_H__
#define __ADD_H__

#endif

The function is to prevent the definition section of the entire function from being continuously carried when the function is continuously called, which causes the code amount of the main program to be too large. The principle of function calling is that the code in the function definition directory is moved to the place where it needs to be used through the header file, and then executed.
Function definition

int Add(int x, int y)
{
    return (x + y);
}

Put it in the directory where the directory is add.c, and put the function of the corresponding function in the directory with prompt meaning, which can better cooperate with others and is readable.
Main function

#include <stdio.h>
#include "add.h"
int main()
{
    int a = 15;
    int b = 25;
    printf("sum=%d\n",Add(a, b));

    return 0;
}

When quoting the header file of a custom function, use double quotation marks "".

The simplest recursion

#include <stdio.h>
int main()
{
    printf("haha\n");
    main();
    return 0;
}//递归常见的错误,栈溢出,stack overflow

This is an unrestricted recursion. The program will stop itself after running for a while, and a warning window will pop up. The reason is that when the program is running, the local variables generated during runtime will be stored in a memory area called the stack. There is no limit. The recursion of, keep calling itself, keep printing "haha", it will fill up the stack.
And this program is also understandable. Recursion is the call of a function to itself. Using the current Internet buzzwords, it is commonly known as a nesting doll.

Design a recursive function to print out 1 2 3 4 in 1234

void print(int n)
{
    if (n > 9)
    {
        print(n / 10);
    }
    printf("%d ", n % 10);

}
#include <stdio.h>
int main()
{
    int num = 0;
    scanf("%d", &num);
    print(num);
    return 0;
}

The first time you want to use recursion to implement a certain function is actually very clueless, even though the teacher is finished, the program is typed out, and the debugging is adjusted step by step, watching the code go line by line, especially It is the call in the function. At the last level, when the call conditions are not met, the program running window will print out the characters one by one. I didn't understand it in the early stage. How the program is executed layer by layer. When I went back, I just forgot where the program was executed. After the teacher drew a picture and explained it, I understood that one step at a time came in, and one step at a time came out. When the last layer no longer meets the conditions and the execution is completed, the pop-up is completed, and after the pop-up to the previous layer, the next statement continues to be executed, and so on.

Do not create temporary variables, find the length of the string

First, write a function that can realize the length of the string, regardless of recursion,
the simplest of course is to directly use the library function to calculate the string length

#include <string.h>
int main()
{
        strlen();
}

Next, use a custom function

int my_strlen(char* str)
{
    int count = 0;
    while (*str != '\0')
    {
        count++;
        str = str + 1;
    }
    return count;
}

The entire string cannot be called directly by the function. You can only use the address of the string as a pointer variable to point to the first character of the string. The call enters the function. After each use, +1 until you see'\ 0'character, the length calculation of the string stops. Count is used as a count to record the length of the string. But what we need is a function that does not use temporary variables to achieve this function.

#include <stdio.h>
int my_strlen(char* str)
{
    if (*str != '\0')
        return 1+my_strlen(str + 1);
    else
        return 0;
}//未使用临时变量进行计数,实现了求字符串长度
int main()
{
    char arr[] = "bit";
    int len = my_strlen(arr);//传送过去的是数组第一个元素的地址,并不是整个数组
    printf("len = %d\n", len);
    return 0;
}

Recursion is still the same. It is easier to understand by drawing a diagram. Visualize the process of program execution and enhance understanding. There are certain restrictions, and each layer of calling functions makes the restrictions closer to not satisfying the if statement. Stop the recursive process. Commonly known as stop dolls.

Recursion and iteration to find factorial

After understanding the previous two recursive examples, I also independently wrote this recursive code for finding factorial. The general idea is to ask for n! , First ask for (n-1)! , Want to ask for (n-1)! , First ask for (n-2)! , Fast forward to want to ask for 2! , Just find 1 first! , So it is still calling itself continuously, the code is as follows:

#include <stdio.h>
int Fac1(int n)
{
    int num = 1;
    int i = 0;
    for (i = 1; i <= n; i++)
    {
        num = i * num;
    }
    return num;
}
int Fac2(int n)
{
    int ret = 1;
    if (n != 0)
         ret = n * Fac2(n - 1);
    else
        return ret;
}
int main()
{
    int n = 0;
    scanf("%d", &n);
    printf("%d!=%d\n",n, Fac1(n));
    printf("%d!=%d\n",n, Fac2(n));
    return 0;
}

Which also used a for loop to write another function to achieve the purpose.

Find the nth Fibonacci sequence

Fibonacci sequence, 1 1 2 3 5 8... Simply put, if you want to know the nth, you have to know the n-1th and n-2th, and you must know the n-1th sum For the n-2th, you have to know the n-2 and n-3th, the n-3th and the n-4th... and so on, but to find the nth recursively, the number of operations required is 2^ n+2^(n-1)+...+2^2+2 operations. When it reaches the 40th or more, the program already has an obvious wait. You need to wait to get the result. The number of calculations In fact, it is already very large. For every n+1, the number of operations will increase twice, and the operation time will increase twice. The code is as follows:

#include <stdio.h>
int Fib1(int n)
{
    if (n <= 2)
        return 1;
    else
        return  Fib1(n - 1) + Fib1(n - 2);
}
int Fib2(int n)
{
    int a = 1, b = 1, c=0;
    int i = 0;
    if (n > 2)
    {
        for (i = 3; i <= n; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
    else
        return 1;
}
int main()
{
    int n = 0;
    scanf("%d", &n);
    int f2 = Fib2(n);
    printf("第%d个斐波那契数列:%d\n", n, f2);
    int f1 = Fib1(n);
    printf("第%d个斐波那契数列:%d\n", n, f1);
    return 0;
}

So there is another function in the above code, which is implemented by iteration without recursion. You can see the time difference between the two functions to achieve the goal when you run it. Therefore, when the number of function calls in the recursion is too large, the amount of calculation is huge , It is necessary to use other means to achieve the goal.

Guess you like

Origin blog.51cto.com/15078858/2593742