下面是個關于遞歸調用簡單但是很能說明問題的例子:
/*遞歸例子*/
#include<stdio.h>
void up_and_down(int);
int main(void)
{
?? up_and_down(1);
?? return 0;
}
void up_and_down(int n)
{
? printf("Level %d:n location %p\n",n,&n); /* 1 */
? if(n<4)
? up_and_down(n+1);
? printf("Level %d:n location %p\n",n,&n); /* 2 */
}
輸出結果
Level 1:n location 0240FF48
Level 2:n location 0240FF28
Level 3:n location 0240FF08
Level 4:n location 0240FEE8
Level 4:n location 0240FEE8
Level 3:n location 0240FF08
Level 2:n location 0240FF28
Level 1:n location 0240FF48
首先,
main()
使用參數
1
調用了函數
up_and_down()
,于是
up_and_down()
中形式參數
n
的值是
1,
故打印語句
#1
輸出了
Level1
。
然后,由于
n
的數值小于
4
,所以
up_and_down()
(第
1
級)使用參數
n+1
即數值
2
調用了
up_and_down()(
第
2
級
).
使得
n
在第
2
級調用中被賦值
2,
打印語句
#1
輸出的是
Level2
。與之類似,下面的兩次調用分別打印出
Level3
和
Level4
。
當開始執行第
4
級調用時,
n
的值是
4
,因此
if
語句的條件不滿足。這時候不再繼續調用
up_and_down()
函數。第
4
級調用接
著執行打印語句
#2
,即輸出
Level4
,因為
n
的值是
4
。現在函數需要執行
return
語句,此時第
4
級調用結束,把控制權返回給該
函數的調用函數,也就是第
3
級調用函數。第
3
級調用函數中前一個執行過的語句是在
if
語句中進行第
4
級調用。因此,它繼
續執行其后繼代碼,即執行打印語句
#2
,這將會輸出
Level3
.當第
3
級調用結束后,第
2
級調用函數開始繼續執行,即輸出
Level2
.依次類推.
注意,每一級的遞歸都使用它自己的私有的變量
n
.可以查看地址的值來證明.
遞歸的基本原理:
1 每一次函數調用都會有一次返回.當程序流執行到某一級遞歸的結尾處時,它會轉移到前一級遞歸繼續執行.
2 遞歸函數中,位于遞歸調用前的語句和各級被調函數具有相同的順序.如打印語句
#1
位于遞歸調用語句前,它按照遞
歸調用的順序被執行了
4
次.
3 每一級的函數調用都有自己的私有變量.
4 遞歸函數中,位于遞歸調用語句后的語句的執行順序和各個被調用函數的順序相反.
5 雖然每一級遞歸有自己的變量,但是函數代碼并不會得到復制.
6 遞歸函數中必須包含可以終止遞歸調用的語句.
再看一個具體的遞歸函數調用的例子:以二進制形式輸出整數
/*輸入一個整數,輸出二進制形式*/
#include<stdio.h>
void to_binary(unsigned long n);
int main(void)
{
? unsigned long number;
? printf("Enter an integer(q to quit):\n");
? while(scanf("%ul",&number)==1)
? {
??? printf("Binary equivalent :");
??? to_binary(number);
??? putchar('\n');
??? printf("Enter an integer(q to quit):\n");
? }
? printf("Done.\n");
? return 0;
?
}
void to_binary(unsigned long n)??? /*遞歸函數*/
{
? int r;
? r=n%2;??? /*在遞歸調用之前計算n%2的數值,然后在遞歸調用語句之后進行輸出.這樣
? 計算出的第一個數值反而是在最后一個輸出*/
? if(n>=2)
? to_binary(n/2);
? putchar('0'+r);/*如果r是0,表達式'0'+r就是字符'0';如果r是1,則表達式的值為
? '1'.注意前提是字符'1'的數值編碼比字符'0'的數值編碼大1.
? ASCII和EBCDIC這兩種編碼都滿足這個條件.*/
? return;
}
?輸出結果為:
Enter an integer(q to quit):
9
Binary equivalent :1001
Enter an integer(q to quit):
255
Binary equivalent :11111111
Enter an integer(q to quit):
?
posted on 2006-11-02 19:13
matthew 閱讀(890)
評論(1) 編輯 收藏 所屬分類:
數據結構與算法設計