Recursion: recursion is everywhere-small talk C language (10)

Source: Internet
Author: User

[Mac 10.7.1 lion intel-based x64 gcc4.2.1]

Q: What is the essence of recursion?

A: recursion can run in terms of the connection between the universe and the completeness of the computer's final commands. In other words, if the parameter of a formula cannot be related to the formula related to the parameter, recursion does not solve it.

Q: Some examples show that recursion is everywhere.

A: For example, You need to calculate the maximum value in an array.

int find_max(int arr[], int size)

From the recursion point of view, the maximum value in an array is decomposed into the maximum value obtained by comparing the first number with the maximum value in the remaining array.

The Code is as follows:

#include <stdio.h>#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));#define MAX(a, b)   ((a) > (b) ? (a) : (b))int find_max(int arr[], int size){    if(size == 1)        return arr[0];    if(size == 2)        return MAX(arr[0], arr[1]);    return MAX(arr[0], find_max(arr + 1, size - 1));}int main(){    int arr[] = {34, 2, 190, 345, 23};    int max_ret = find_max(arr, sizeof(arr) / sizeof(arr[0]));    PRINT_D(max_ret)        return 0;}

Running result:

Similarly, the minimum value in the array, the length of the string, and the sum of all elements in the array are also similar.

Q: Can I use recursion to reverse a string?

A: Yes. If you need to reverse a string, you can think like this: it will first reverse the first and last characters, and then reverse the string in the middle. The Code is as follows:

#include <stdio.h>#define PRINT_STR(str)      printf(#str" is %s\n", (str));#define SWAP(type, a, b)    {type temp = a; a = b; b = temp;}void    reverse_str(char *str, int len){    if(len <= 1)        return;    SWAP(char, str[0], str[len - 1]);    reverse_str(str + 1, len - 2);}int main(){    char buf[] = "hello world";    reverse_str(buf, strlen(buf));    PRINT_STR(buf)    return 0;}

Running result:

Q: How do I use recursion to output an integer string?

A: You can modulo 10 for this integer to get the final output of the data. Continue to divide the recursive integer by the remaining 10 values.

#include <stdio.h>void    print_int(int n){    if(n >= 10)        print_int(n / 10);    printf("%d", n % 10);}int main(){    print_int(123);    return 0;}

Execution result:

Similarly, it is similar to output in reverse order to determine whether it is a return.

Q: How to use recursion to output an integer that corresponds to the number of bits 1 in binary format?

A: Its value can be seen as: If the integer N is an odd number, then the sum of the n/2 binary values containing the number of bits 1 plus 1 is returned; if it is an even number, returns the number of bits in the n/2 binary;

The Code is as follows:

#include <stdio.h>#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));int int_has_1_count(int n){    if(n <= 1)        return n % 2;    if(n % 2 == 0)        return int_has_1_count(n / 2);    else        return int_has_1_count(n / 2) + 1;}int main(){    PRINT_D(int_has_1_count(1099))    return 0;}

Running result:

The binary format of 1099 is: 10001001011. It can be determined that the number of binary bit 1 is 5.

Likewise, binary search and binary tree traversal are similar.

Q: How can we use recursion to calculate the value of one number plus another number M?

A: This process is divided into M auto-increment operations. Example:

#include <stdio.h>#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));int add_x(int *n, int add_num){    if(add_num < 1)        return *n;    if(add_num == 1)        return ++(*n);    else    {        ++(*n);        return add_x(n, add_num - 1);    }}int main(){    int n = 12;    PRINT_D(add_x(&n, 3))    return 0;}

Running result:

Similarly, the operations between two variables can be converted into smaller operations, and you can see how to use smaller operations to achieve large operations.

Q: three different elements, ABC, are all the forms of the output arrangement. For example, ABC, ACB, and BCA.

A: The output large process is regarded as the need to output the three elements. The small process is to output one element and can only be output once. The Code is as follows:

#include <stdio.h>#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));// a, b, c : the output char;// print_count_a, print_count_b, print_count_c : can print count// output: the output array// output_index: current print indexvoid    print_abc_all_styles(char a, char b, char c,                              int print_count_a,                              int print_count_b,                             int print_count_c,                             char output[],                             int  output_index){    if(print_count_a + print_count_b + print_count_c == 0)    {        printf("%c%c%c", output[0], output[1], output[2]);        printf("\n");        return;    }        if(print_count_a == 1)    {        output[output_index] = a;        --print_count_a;        print_abc_all_styles(a, b, c,                              print_count_a,                              print_count_b,                              print_count_c,                             output, output_index + 1);        ++print_count_a;            }    if(print_count_b == 1)    {        output[output_index] = b;        --print_count_b;        print_abc_all_styles(a, b, c,                              print_count_a,                              print_count_b,                              print_count_c,                             output, output_index + 1);        ++print_count_b;    }    if(print_count_c == 1)    {        output[output_index] = c;        --print_count_c;        print_abc_all_styles(a, b, c,                              print_count_a,                              print_count_b,                              print_count_c,                             output, output_index + 1);        ++print_count_c;    }}

Running result:

Similar methods can be used for arrangement or combination of ABC, AABC, abbc, and aabbcc;

A more general code:

#include <stdio.h>#include <string.h>#include <stdbool.h>#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));static  bool    isExist(const char *str, const int str_size, char ch){    int i;    for(i = 0; i < str_size; ++i)    {        if(str[i] == ch)            return true;    }    return false;}void    print_abc_all_styles(const char *elements,  // be outputed elements                             int max_print_count,   // max printed elements                             char output[],     // output string                             const int  output_size,  // output string size                             int  output_index) // current output index{    int i;    if(max_print_count == 0)    {        int i = 0;        for(; i < output_size; ++i)            printf("%c", output[i]);        printf("\n");        return;    }        for(i = 0; i < strlen(elements); ++i)    {        if(!isExist(output, output_index, elements[i]))        {            output[output_index] = elements[i];            --max_print_count;            print_abc_all_styles(elements, max_print_count,                                 output, output_size, output_index + 1);            ++max_print_count;        }    }}int main(){    char buf[4] = {0};    print_abc_all_styles("abc", 3, buf, 3, 0);    return 0;}

Q: How to output a string?

A: First output the first one, and then output the rest as a string;

Q: How do I download an object?

A: First download the first byte, and then continue to use the previous method for download;

Q: How can I fly to the moon?

A: First fly the first section, then fly all the remaining sections;

Q: How to make a dish?

A: First cook the first part of the dish and then make the remaining part;

Q: How can I catch a girl?

A: On the first day, I used a certain method to talk to her. Later I used a similar but possibly different method to talk to her, do what to do, and finally fix her. However, it cannot be as unstable as a computer.

Q: How can I go home?

A: Do something closer to your home and continue to do something similar;

Q: How do I access the Internet?

A: First prepare for surfing the Internet and then do the rest;

Q: How to eat?

A: take the first bite, and then finish all the meals.

Q: How do I write code?

A: First write the first sentence and then write all the code;

Q :.........

A :.........

In short, do not think that the answer is too simple, but that recursion is simple.

Xichen

11:50:49

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.