C++Recursion , recursive function ( C++递归 , 递归函数) 两个程序范例

 Example 1:
 
  

// recur.cpp -- using recursion
#include <iostream>
void countdown(int n);
int main()
{
countdown(4); // call the recursive function
return 0;
}

void countdown(int n)
{
using namespace std;
cout << "Counting down ... " << n <<"(n at "<< &n <<")"<<endl;
if (n > 0)
countdown(n-1); // function calls itself
cout << n << ": Layer ... "<<"(n at "<< &n <<")"<<endl;
}


result:
 
  

Counting down ... 4(n at 0xbf892df0)
Counting down ... 3(n at 0xbf892dd0)
Counting down ... 2(n at 0xbf892db0)
Counting down ... 1(n at 0xbf892d90)
Counting down ... 0(n at 0xbf892d70)
0: Layer ... (n at 0xbf892d70)
1: Layer ... (n at 0xbf892d90)
2: Layer ... (n at 0xbf892db0)
3: Layer ... (n at 0xbf892dd0)
4: Layer ... (n at 0xbf892df0)





Example 2:
 
 

// ruler.cpp -- using recursion to subdivide a ruler
#include <iostream>
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 = 1; i < Len - 2; i++)
ruler[i] = ' ';
ruler[Len - 1] = '\0';
int max = Len - 2;
int min = 0;
ruler[min] = ruler[max] = '|';
std::cout << ruler << std::endl;
for (i = 1; i <= Divs; i++)
{
subdivide(ruler,min,max, i);
std::cout << ruler << std::endl;
for (int j = 1; j < Len - 2; j++)
ruler[j] = ' '; // reset to blank ruler
}
return 0;
}
void subdivide(char ar[], int low, int high, int level)
{
if (level == 0)
return;
int mid = (high + low) / 2;
ar[mid] = '|';
subdivide(ar, low, mid, level - 1);
subdivide(ar, mid, high, level - 1);
}


Result is:
 
  

| |
| | |
| | | | |
| | | | | | | | |
| | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值