Bootstrap

递归函数初探

 包含一个递归调用的递归

示例1

#include <iostream>
#include<string>
#include<array>
using namespace std;

void countdown(int n);

int main()
{
	countdown(4);
	return 0;
}void countdown(int n)
{
	cout << "counting down ..." << n << endl;
	if (n > 0)
	{
		countdown(n - 1);
	}
	cout << n << ": Kaboom!\n";
}

示例2

#include <iostream>
#include<string>
#include<array>
using namespace std;

void countdown(int n);

int main()
{
	countdown(4);
	return 0;
}
void countdown(int n)
{
	cout << "counting down ..." << n << " ( n at "<< &n<< " )" << endl;
	if (n > 0)
	{
		countdown(n - 1);
	}
	cout << n << ": Kaboom!" << " ( n at " << &n << " )" << endl;
}

 每层调用都创建一个自己的变量

包含多个递归调用的递归

#include <iostream>
#include<string>
#include<array>
using namespace std;

const int Len = 66;
const int Divs = 6;
void subdivide(char ar[],int low,int high,int level);

int main()
{
	char ruler[Len];
	int i;
	for (i = 0; i < Len; i++)
	{
		ruler[i] = ' ';
	}
	ruler[Len - 1] = '\0';
	int max = Len - 2;
	int min = 0;
	ruler[min] = ruler[max] = '|';
	cout << ruler << endl;
	for (i = 0; i <= Divs; i++)
	{
		subdivide(ruler, min, max, i);
		cout << ruler << endl;
		for (int j = 1; j < Len - 2; j++)
			ruler[j] = ' ';
	}
	return 0;
}

void subdivide(char ar[], int low, int high, int level)
{
	if (level == 0)
	{
		return;
	}
	int mid = (low + high) >> 1;
	ar[mid] = '|';
	subdivide(ar, low, mid, level - 1);
	subdivide(ar, mid, high, level - 1);
}

;